I am making a chrome extension to find a string if text in DOM and replace it with something else.
What is the best way to traverse the whole DOM element wise and replace the text in DOM. I Thought of placing document.body
in a variable and then process it as a qeue but I am confused that how to do so
This is my Code:
flag = true;
var word = 'word',//word to replace
queue = [document.body],
curr;
try {
while ((curr = queue.pop()) || flag) {
if (!(curr.textContent.match(word))
continue;
for (var i = 0; i < curr.childNodes.length; ++i) {
if (!flag) break;
switch (curr.childNodes[i].nodeType) {
case Node.TEXT_NODE: // 3
if (curr.childNodes[i].textContent.match(word)) {
curr.childNodes[i].textContent("xxx");//replacing the word
console.log('Found!');
flag = false;
break;
}
break;
case Node.ELEMENT_NODE: // 1
queue.push(curr.childNodes[i]);
break;
}
}
}
} catch (e) {
//
}