Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace text at top-level of node without breaking formatting of children

Tags:

javascript

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/

like image 963
Tyilo Avatar asked Dec 11 '25 15:12

Tyilo


1 Answers

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.

like image 138
Felix Kling Avatar answered Dec 14 '25 04:12

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!