繁体   English   中英

如何在span标签中包装DOM关键字

[英]How to wrap DOM keywords in a span tag

我正在编写一个JavaScript脚本,它将遍历DOM并将特定的关键字包装在<span>标记中。 我希望我的script将出现的单词pan包裹在<span>以便可以使用<span style='color: red' 我实际上并不想使用pan这个词,我只是以它为例。

我已经在这里查看了许多类似的帖子,但是都没有解决我的问题。 大多数都是核的,过于复杂和混乱的,或者是过于简化的,并且没有按照我的预期工作。

到目前为止,这是我写的内容:

 <html> <body> <p>My <span style='font-weight: bold'>favorite</span> kitchen item is the pan.</p> <p>A pan can also be used as a weapon.</p> <script> // walk the document body function walk (node) { // if text node if (node.nodeType == 3) { // will always be an element const parent = node.parentNode; // ignore script and style tags const tagName = parent.tagName; if (tagName !== 'SCRIPT' && tagName !== 'STYLE') { // wrap occurrences of 'pan' in a red `<span>` tag const span = '<span style="color: red">pan</span>'; parent.innerHTML = parent.innerHTML.replace (/pan/g, span) } } node = node.firstChild; while (node) { walk (node); node = node.nextSibling; } } walk (document.body) </script> </body> </html> 

这段代码大多数时候都按预期运行。 但是,在此示例中,事实并非如此。 如果你运行该代码, 会是这个结果。

我知道是什么原因造成的。 但是,我不知道如何解决它。

两个文本节点,“ My和“ kitchen item is the pan. 有一个带有以下innerHTML的父元素: My <span style="font-weight: bold">favorite</span> kitchen item is the pan. <span>的“ pan”已被替换,并引起了问题。

如果我使用parentNode.textContent而不是parentNode.innerHTML ,则不会将其包装在<span>标记中,而是将其插入为可见文本。

我知道可以通过将/pan/g更改为/\\bpan\\b/g来解决此问题,但这只能解决我创建的示例。 我需要将<span>标记仅插入文本内容,而不是标记名称或其他HTML。

我该怎么办?

使用转义的搜索字符串搜索给定的htmlString 这样做(使用适当的转义符)将有助于避免出现诸如匹配HTML标签(例如<s pan > )或子字符串(例如Pan dora)之类的问题。

 /* highlight(selector, string) @ Params: selector [String]: Same syntax as CSS/jQuery selector string [String]: Seach string */ // A: Get the htmlString of the target's content // B: Escape the search string // C: Create a RegExp Object of the escaped search string // D: Find and replace all matches with match wrapped in a <mark> // E: Remove original HTML // F: Insert new HTML function highlight(selector, string) { let dom = document.querySelector(selector); let str = dom.innerHTML; //A let esc = `(?!(?:[^<]+>|[^>]+<\\\\/a>))\\\\b(${string})\\\\b`; //B let rgx = new RegExp(esc, "gi"); //C let txt = str.replace(rgx, `<mark>$1</mark>`); //D dom.innerHTML = ''; //E dom.insertAdjacentHTML('beforeend', txt); //F } highlight('body', "pan"); 
 <html> <body> <p>My <span style='font-weight: bold'>favorite</span> kitchen item is the pan.</p> <p>A pan can also be used as a weapon.</p> <p>Pan was the Greek god of the wild.</p> <p>Eboli was breifly a pandemic threat.</p> </body> </html> 

暂无
暂无

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

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