0

Not a dupe... Non of mentioned work.. Trying to highlight a word with a google extension. Running this as a content script, but it doesn't seem to be a working solution... What have I missed?

var elements = document.getElementsByTagName('*');

for (var i = 0; i < elements.length; i++) {
    var element = elements[i];

    for (var j = 0; j < element.childNodes.length; j++) {
        var node = element.childNodes[j];

        if (node.nodeType === 3) {
            var text = node.nodeValue;
            var replacedText = text.replace("Target Text", "<font color='red'>Target Text</font>");

            if (replacedText !== text) {
                element.replaceChild(document.createTextNode(replacedText), node);
            }
        }
    }
}
Jessica Ray
  • 65
  • 2
  • 5

1 Answers1

0

In this line you're asking for the child nodes of a node:

 var node = element.childNodes[j];

This will always return an array of nodes, even if there's only one node. So this condition will never be true:

if (node.nodeType === 3)

You're actually getting all nodes and you'll have to loop over those as well.

Nate
  • 6,384
  • 3
  • 25
  • 30