javascript - 如果 innerHTML 包含 x、y、z 等,则 replaceWith——需要针对多个 innerHTML 变体的解决方案

标签 javascript html json

我有一个简短的脚本,它在 innerHTML 中查找具有特定文本的特定类,然后使用 replaceWith 替换整个元素。当只有一段特定的文本时,此方法非常有用,但我有几个项目要查找和替换。

下面的 HTML 代码是经过简化的。基本上,有另一个脚本可以找到特定的术语,并在这些术语第一次出现时添加一个带有定义的弹出窗口。有一些术语我想省略,但修改其他脚本是不可能的。我放在一起的第一个解决方案涉及找到弹出类,查看它的 innerHTML 以获得一致的开头(它总是以 term 开头,紧接着是一个 span 标签)然后用 term 替换整个元素作为普通文本(“term” ).

let glossaryTerms = document.getElementsByClassName('popup');
for (let x = 0; x < glossaryTerms.length; x++) {
    let term = glossaryTerms[x];
    let content = term.innerHTML.trim();
        if (content.includes('term\<span')) {
           term.replaceWith('term');
        }
}
<p>Sample text for this example. Then there's a word with a definition popup <a  href="#" class="popup #text">term<span class="popupBody">This is the definition text that appears in the popup eventually...</span></a>.</p>

那个脚本工作得很好,但我可能有几十个术语。

例如: 苹果 香蕉 仙人掌

等等。

非常感谢这里的任何建议。例如,我想知道这些术语是否可以存储在 JSON 文件中,但我不知道从哪里开始。

最佳答案

提取第一个文本(在第一个子元素之前)的方法是:

node.childNodes[0].nodeValue.trim();

...因为这会将 span 节点视为第二个节点,前提是它前面有文本。

还有第二个问题:getElementsByClassName 返回的集合是一个事件集合,即当您将那些弹出节点替换为纯文本时,您实际上减小了大小那个集合。那么第二个元素是什么,突然变成了第一个(在索引 0 处),但是你的循环增加了索引,所以你跳过一个节点。

一个解决方案是使用非实时替代querySelectorAll:

let terms = new Set(["apple", "pear"]); // Only do something for these terms
for (let node of document.querySelectorAll('.popup')) {
    let term = node.childNodes[0].nodeValue.trim();
    if (terms.has(term)) node.replaceWith(term);
}
<p>Sample text for this example. Then there's a word with a definition popup 
<a  href="#" class="popup #text">apple<span class="popupBody">
This is the definition text that appears in the popup eventually...</span></a>.</p>

<p>Sample text for this example. Then there's a word with a definition popup 
<a  href="#" class="popup #text">pear<span class="popupBody">
This is the definition text that appears in the popup eventually...</span></a>.</p>

关于javascript - 如果 innerHTML 包含 x、y、z 等,则 replaceWith——需要针对多个 innerHTML 变体的解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54044262/

相关文章:

java - JSON 字符串验证 [Spring Boot] - 约束零值

javascript - 同一对象的严格相等比较算法

javascript - 如何减少 Jquery 中的这一行?

javascript - 如何将变量注入(inject)子指令

html - Div 设置为绝对位置,不会将其他 div 向下推到它下面

javascript - 无法读取未定义的属性 'online'

javascript - 在 PHP 中使用定义的 jQuery 变量

javascript - 如何获取 HTML 输入元素中光标/插入符的位置?

JavaScript:重构,避免 array.push()

javascript - 如何防止 document.write 超出 Div 框?