我有这段代码可以在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,用其他东西代替它,但是我尝试了一些方法,但我却做不到。我在做什么错了?
答案 0 :(得分:1)
这将为您提供所需的结果(我决定跳过'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>
希望这会有所帮助