0

I need to use JavaScript to loop through the DOM tree of a webpage and replace every instance of the word 'hipster' with a different word UNLESS it is part of a link or image src. Example, if 'hipster' appears in a paragraph, it should be replaced.

But if it's in the src="" url for an image, that should not be replaced because if it replaces that word in a url, the url obviously breaks.

I've been having a really hard time implementing this. Here's one thing I tried:

var items = document.getElementsByTagName("*");
  var i = 0;
  for (i = 0; i < items.length; i++){
     if(i.nodeType == 3){
        i.html().replace(/hipster/gi, 'James Montour');
     }
     else{
       //do nothing for now
     }
  }
2
  • 1
    Do you want to check your question? It doesn't make sense. "So if 'hipster' appears in a paragraph, for example, it should be replaced. But if it's in the src url for an image, that should be replaced." Didn't you mean "shouldn't" in one of your cases? Commented Aug 30, 2014 at 2:00
  • 1
    Same again, I'm afraid. Now your 1st & 2nd paras say the opposite of each other. Commented Aug 30, 2014 at 2:06

2 Answers 2

3

You’re close, but:

  • document.getElementsByTagName('*') will never return text nodes; it gets elements only (and comment nodes in old versions of IE)

  • Text nodes don’t have an html() method

  • replace doesn’t modify strings in place

With that in mind, you can get every child of every element, check their types, read their nodeValues, and, if appropriate, replace the entire node:

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(/hipster/gi, 'James Montour');

            if (replacedText !== text) {
                element.replaceChild(document.createTextNode(replacedText), node);
            }
        }
    }
}

Try it out on this page!

Sign up to request clarification or add additional context in comments.

1 Comment

Worked like a charm! I had never worked with nodeType before so got kind of lost there.
-1

To use variables instead of 'hipster' replace:

var replacedText = text.replace(/hipster/gi, 'James Montour');

with these lines:

var needle = 'hipster';
var replacement = 'James Montour';
var regex = new RegExp(needle, "gi");
var replacedText = text.replace(regex, replacement);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.