gpt4 book ai didi

javascript - 在html body中找到一个单词后,将其替换为另一个

转载 作者:行者123 更新时间:2023-11-29 23:01:57 26 4
gpt4 key购买 nike

我有这段代码可以在 html 页面的整个正文中找到一个词

var word = "active",
queue = [document.body],
curr
;
while (curr = queue.pop()) {
if (!curr.textContent.match(word)) continue;
for (var i = 0; i < curr.childNodes.length; ++i) {
switch (curr.childNodes[i].nodeType) {
case Node.TEXT_NODE : // 3
if (curr.childNodes[i].textContent.match(word)) {
console.log("Found!");
console.log(curr);
// you might want to end your search here.
word.replace('active', 'test');
}
break;
case Node.ELEMENT_NODE : // 1
queue.push(curr.childNodes[i]);
break;
}
}
}

我想做的是,如果找到了 active,将其替换为其他东西,但我已经尝试了一些方法,但我无法做到。我做错了什么?

最佳答案

这将给出您正在寻找的结果(我决定跳过 'SCRIPT' nodeName 这样您就不会意外修改任何代码:

let word = "active";
let queue = [document.body];
let curr;

while (curr = queue.pop()) {
if (!curr.textContent.match(word) || curr.nodeName === 'SCRIPT') continue;
for (var i = 0; i < curr.childNodes.length; ++i) {
if (curr.childNodes[i].nodeName === 'SCRIPT') continue;
switch (curr.childNodes[i].nodeType) {
case Node.TEXT_NODE: // 3
if (curr.childNodes[i].textContent.match(word)) {
console.log("Found!", `'${curr.childNodes[i].textContent}'`);
curr.childNodes[i].textContent = curr.childNodes[i].textContent.replace('active', 'test');
}
break;
case Node.ELEMENT_NODE: // 1
queue.push(curr.childNodes[i]);
break;
}
}
}
<div>asdf</div>
<span>active</span>
<div>asdf</div>

希望对你有帮助,

关于javascript - 在html body中找到一个单词后,将其替换为另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55427110/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com