"Hi I am text"
<...">

Replace only text inside div using jquery

I have a div like:

<div id="one"> <div class="first"></div> "Hi I am text" <div class="second"></div> <div class="third"></div> </div> 

I am trying to change only the text from "Hello, I am text" to "Hello, I am replaced" using jquery. It may be easy, but I cannot do it.

Using $('#one').text('') just empties the entire #One div.

+95
javascript jquery
Aug 08 2018-12-12T00:
source share
6 answers

The text should not be on its own. Put it in the span element.

Change it like this:

 <div id="one"> <div class="first"></div> <span>"Hi I am text"</span> <div class="second"></div> <div class="third"></div> </div> 
 $('#one span').text('Hi I am replace'); 
+126
Aug 08 2018-12-12T00:
source share

Find the text nodes ( nodeType==3 ) and replace textContent :

 $('#one').contents().filter(function() { return this.nodeType == 3 }).each(function(){ this.textContent = this.textContent.replace('Hi I am text','Hi I am replace'); }); 

Real-time example: http://jsfiddle.net/VgFwS/

+108
Aug 08 2018-12-12T00:
source share

You need to set the text for something other than an empty string. In addition, the .html () function should do this while maintaining the structure of the HTML div.

 $('#one').html($('#one').html().replace('text','replace')); 
+11
Aug 08 '12 at 14:57
source share

If you really know the text you are about to replace, you can use

 $('#one').contents(':contains("Hi I am text")')[0].nodeValue = '"Hi I am replace"'; 

http://jsfiddle.net/5rWwh/

or

 $('#one').contents(':not(*)')[1].nodeValue = '"Hi I am replace"'; 

$('#one').contents(':not(*)') selects non-element child nodes, in this case the text nodes and the second node is the one we want to replace.

http://jsfiddle.net/5rWwh/1/

+8
Aug 08 2018-12-12T00:
source share

Another approach is to save this element, change the text, and then add this element back

 const star_icon = $(li).find('.stars svg') $(li).find('.stars').text(repo.stargazers_count).append(star_icon) 
0
May 22 '16 at 8:06
source share

Just in case, if you cannot change the HTML. Very primitive, but short and works. (It will empty the parent div, so the child divs will be deleted)

 $('#one').text('Hi I am replace'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="one"> <div class="first"></div> "Hi I am text" <div class="second"></div> <div class="third"></div> </div> 
0
May 15 '18 at 3:03
source share



All Articles