簡體   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