简体   繁体   English

有条件地从html字符串中查找和替换html标签

[英]Finding and replacing html tags conditionally from an html string

I have access to an html string in which I want to search for a specific set of values. 我可以访问要在其中搜索一组特定值的html字符串。 So lets say I want to match something from an array... 所以可以说我想匹配数组中的某项...

var array1 = [value1, value2, value3] var array1 = [value1,value2,value3]

If I find value1 in the html string, i want to add a highlight class to that value so it gets highlighted. 如果我在html字符串中找到value1,我想向该值添加突出显示类,以使其突出显示。

 var str = htmlString var res = str.replace('<thead>','<thead class="highlight">'); htmlString = res 

Using this i can highlight all the theads, but how could I write it so that I only highlight the theads that contain one of those array values inside of it? 使用这个我可以突出显示所有theads,但是我怎么写它以便只突出显示其中包含那些数组值之一的thead?

Here's a solution for browser that parses the HTML string into a DOM element, query the DOM tree and manipulate the classList of each selected element, then returns the HTML as a string. 这是一种用于浏览器的解决方案,该解决方案将HTML字符串解析为DOM元素,查询DOM树并操纵每个选定元素的classList ,然后将HTML作为字符串返回。

 function addClassToElementsByTagName(html, tagName, className) { var tempElement = document.createElement('div'); tempElement.innerHTML = html; var elements = tempElement.querySelectorAll(tagName); elements.forEach(function(element) { element.classList.add(className); }); return tempElement.innerHTML; } var htmlString = '<table>\\n\\t<thead>\\n\\t<tr>\\n\\t\\t<th>Column 1</th>\\n\\t\\t<th>Column 2</th>\\n\\t\\t<th>Column 3</th>\\n\\t</tr>\\n\\t</thead>\\n</table>'; var result = addClassToElementsByTagName(htmlString, 'thead', 'highlight'); console.log(result); 

Gotchas 陷阱

Keep in mind that element.querySelectorAll() and element.classList.add() are not universally supported. 请记住,不普遍支​​持element.querySelectorAll()和element.classList.add()。 Check out caniuse.com for information regarding each feature. 请访问caniuse.com,以获取有关每个功能的信息。

Also, this is completely dependent on how the browser parses your HTML. 另外,这完全取决于浏览器如何解析HTML。 If the HTML fails to parse or parses incorrectly, you will experience problems. 如果HTML解析失败或解析错误,您将遇到问题。 The .innerHTML property also makes no guarantee that the whitespace provided in the original string will be preserved in the result. .innerHTML属性也不保证原始字符串中提供的空白将保留在结果中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM