If I have the following html code:
<div id="element">
Qwerty Foo Bar
<span style="color: red;">This text should/will never be changed by the script.</span>
</div>
And I want to change “Foo” to “baz”, I can do the following:
var element = document.getElementById('element');
element.innerText = element.innerText.replace('Foo', 'baz');
However this will destroy the formatting of the red text.
How can you do this?
I don’t need cross-browser support, only support for chrome and I don’t want to use a js framework. jsFiddle: http://jsfiddle.net/cLzJD/3/
You can iterate over the children and only modify text nodes:
DEMO
Notes:
If you want to replace all occurrences of
Foo, you have to use a regular expression:replace(/Foo/g, 'baz').The advantage of this approach is that event handlers bound through JavaScript will stay intact. If you don’t need this,
innerHTMLwill work as well.