Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
70
rated 0 times [  76] [ 6]  / answers: 1 / hits: 39046  / 13 Years ago, wed, may 25, 2011, 12:00:00

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?


More From » string

 Answers
14

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)


[#92046] Tuesday, May 24, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daijab

Total Points: 60
Total Questions: 99
Total Answers: 110

Location: Bosnia and Herzegovina
Member since Thu, Jun 24, 2021
3 Years ago
;