我的目标是用span元素替换文档p标记中的每个单词。虽然下面的代码很好地处理了第一种情况,但下面的代码重叠,并开始完全破坏P标记的HTML结构。
输出想知道如果我的方法是一个错误的,或者需要一些魔法只影响标签之间的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;};
旨在最终构建一个chrome扩展,突出显示任何页面上任何单词的前1/2个字符。这将有助于有阅读障碍的人更快地阅读网页。为上下文在github上附加一个链接到整个repo。
好的,所以我最终用一个新的span元素代替了整个TextNode。这样我就可以准备整个元素并将其附加到其父元素上。工作完美,不需要正则表达式....
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;};