Reputation: 1792
i have this code that finds a word in the entire body of a html page
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;
}
}
}
And what i'm trying to do is if active is found, replace it with something else but i have tried some ways and i wasnt able to do it. What i'm doing wrong?
Upvotes: 2
Views: 257
Reputation: 4557
This would give the result you are looking for (I decided to skip of 'SCRIPT'
nodeName
's so you do not accidentally modify any code:
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>
Hope this helps,
Upvotes: 1