简体   繁体   中英

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)?

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

The best way to resolve the problem is just add the text inside another element and find the previous element using prev() method of Jquery ....

You can check the link :

http://api.jquery.com/prev

HTML CODE :

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

JQUERY CODE :

$ = jQuery.noConflict();
$("#checkit").delegate('#clickit' , 'click' , function(){
   $(this).prev().html('your text here..');
});

And code is also created on the jsfiddle :

http://jsfiddle.net/paragkuhikar/VxJBD/

Please check it...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM