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:
var children = element.childNodes,
child;
for(var i = children.length; i--; ) {
child = children[i];
if(child.nodeType === 3) {
child.nodeValue = child.nodeValue.replace('Foo', 'baz');
}
}
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, innerHTML will work as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With