Replace only text inside a div using jquery

Replace only text inside a div using jquery

I have a div like:

“Hi I am text”

I am trying to change only the text from “Hi I am text” to “Hi I am replace” using jquery.
This might be easy but I am not able to do it.
Using $(‘#one’).text(”) just empties the whole #One div.


Solution 1:

Text shouldn’t be on its own. Put it into a span element.

Change it to this:

<div id="one">
       <div class="first"></div>
       <span>"Hi I am text"</span>
       <div class="second"></div>
       <div class="third"></div>
$('#one span').text('Hi I am replace');

Solution 2:

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

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

Live example:

Solution 3:

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


Solution 4:

If you actually know the text you are going to replace you could use

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


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

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

Solution 5:

Just in case if you can’t change HTML. Very primitive but short & works.

$('#one').text('Hi I am replace');
<script src=""></script>

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

Solution 6:

Another approach is keep that element, change the text, then append that element back

const star_icon = $(li).find('.stars svg')