Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace text inside an element

I'm needing to replace a portion of text inside arbitrary elements. I won't know anything about the structure of the element, including about any child elements it may have, but I have to assume there may be child elements with attached bindings. An example might be:

<div id="checkit">
  Lorem ipsum textum checkum.
  <input type="button" id="clickit" value="Click Me" />
</div>

Now, if I want to replace 'ipsum' with something else, I could grab the contents of #checkit with innerHTML, run replace on it, then set its innerHTML with the new text, but if a binding has been set on #clickit, the binding will be lost when innerHTML is updated.

I don't really need or want to replace the entire innerHTML of the element but I'm not sure how else to replace a portion of text in the element.

So my question is twofold:

  1. Suggestion on how to replace a portion of text within #checkit
  2. Suggestion on how to replace innerHTML without losing bindings (or a way to save bindings inside #checkit and reapply them after replacing innerHTML)?
like image 418
Chris Roberts Avatar asked Jan 26 '26 04:01

Chris Roberts


1 Answers

Suggestion on how to replace a portion of text within #checkit

You can use this way t replace only the text content without disturbing any element inside of it.

$('#checkit').contents().each(function(){
    if(this.nodeType===3) //select only the text nodes
    {
      this.nodeValue = this.nodeValue.replace(/u/g,'Z'); //replace all u with z
    }
});

Demo

Suggestion on how to replace innerHTML without losing bindings (or a way to save bindings inside #checkit and reapply them after replacing innerHTML)?

If you want to replace innerHTML and keep the binding intact, you may bind the event again or use event delegation using .on() in jquery. so that event is attached to the elements present in the DOM now as well as for the future, that matches the selector, without having to bind them again.

See documentation

like image 113
PSL Avatar answered Jan 28 '26 18:01

PSL



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!