简体   繁体   English

如何避免在 innerHTML string.replace() 期间影响 childNodes 中的 HTML 标签?

[英]How to avoid affecting HTML tags in childNodes during innerHTML string.replace()?

I am aiming to replace each word in a document P tags with a span element.我的目标是用 span 元素替换文档 P 标签中的每个单词。 While the below code does the trick well for the first case, the following ones overlap, and start to destroy the HTML structure of our P tag completely.虽然下面的代码在第一种情况下做得很好,但下面的代码重叠,并开始完全破坏我们 P 标签的 HTML 结构。 See image for unwanted output请参阅图像以获取不需要的输出

Wondering if my approach is a wrong one, or would need some sorcery to only effect the innerHTML between the tags?想知道我的方法是错误的,还是需要一些魔法才能只影响标签之间的 innerHTML?

const runBionic = (node: ChildNode, paragraph: HTMLElement):HTMLElement => {
if (node.textContent === null) return paragraph;
const originalWords:string[] = node.textContent.split(" ");
const filteredWords: string[] = originalWords.filter(word => word!=="" && word !== "\n");
console.log("Filtered words: ", filteredWords);
//replace each word with a span element
filteredWords.forEach(word => {
    const modifiedWord = `<span style='font-weight: bold;'>${word}</span>`;
    console.log("REPLACING ", word, "WITH ", modifiedWord);
    paragraph.innerHTML = paragraph.innerHTML.replaceAll(word,modifiedWord);
});
return paragraph;};

Aiming to eventually build a chrome extension that highlights the first 1/2 of the characters of any word on any page.旨在最终构建一个 chrome 扩展,突出显示任何页面上任何单词的前 1/2 字符。 This will help dyslexic people read the web faster.这将帮助有阅读障碍的人更快地阅读网络。 Attaching a link to the whole repo on github for context.在 github 上附加指向整个 repo的链接以获取上下文。

Okay, so I ended up with replacing the whole TextNode with a new span element instead.好的,所以我最终用一个新的 span 元素替换了整个 TextNode。 This way I can prepare the whole element and append it to its parent.这样我可以准备整个元素并将其附加到其父元素。 Works perfectly, no regex needed....完美运行,不需要正则表达式....

const replaceNode = (node: ChildNode)=>{
if (node.textContent === null) return node;
const newChild = document.createElement("span");
const words: string[] = node.textContent.split(" ").filter(word => word!=="" && word !== "\n");
const HTMLstring: string = spannify(words);
newChild.innerHTML = HTMLstring;
return newChild;};

const spannify = (words : string[]) : string=>{
let HTMLstring = "";
words.forEach(word =>{
    const span = `<span> ${word} </span>`;
    HTMLstring += span;
});
return HTMLstring;};

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

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