Search code examples
javascriptstringsearchdomtext

Finding the DOM element with specific text and modify it


I'm trying to figure out how to, in raw javascript (no jQuery, etc.), find an element with specific text and modify that text.

My first incarnation of the solution... is less than adequate. What I did was basically:

var x = document.body.innerHTML;
x.replace(/regular-expression/,"text");
document.body.innerHTML = x;

Naively I thought I succeeded with flying colors, especially since it was so simple. So then I added an image to my example and thought I could check every 5 seconds (because this string may enter the DOM dynamically)... and the image flickered every 5 seconds.

Oops.

So, there has to be a correct way to do this. A way that specifically singles out a specific DOM element and updates the text portion of that DOM element.

Now, there's always "recursively search through the children till you find the deepest child with the string" approach, which I want to avoid. And even then, I'm skeptical about "changing the innerHTML to something different" being the correct way to update a DOM element.

So, what's the correct way to search through the DOM for a string? And what's the correct way to update a DOM element's text?


Solution

  • Now, there's always "recursively search through the children till you find the deepest child with the string" approach, which I want to avoid.

    I want to search for an element in an unordered random list. Now, there's a "go through all the elements till you find what you're looking for approach", which I want to avoid.

    Old-timer magno tape, record, listen, meditate.

    Btw, see: Find and replace text with JavaScript on James Padolsey's github
    (also hig blog articles explaining it)