Replace only text inside a div using jquery

JavascriptJquery

Javascript Problem Overview


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 "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.

Javascript Solutions


Solution 1 - Javascript

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>
</div>

$('#one span').text('Hi I am replace');

Solution 2 - Javascript

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

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

Note that as per the docs you can replace the hard-coded 3 in the above with Node.TEXT_NODE which is much clearer what you're doing.

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

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.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>

Solution 3 - Javascript

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.

$('#one').html($('#one').html().replace('text','replace'));

Solution 4 - Javascript

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"';

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 text nodes and the second node is the one we want to replace.

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

Solution 5 - Javascript

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

const star_icon = $(li).find('.stars svg')
$(li).find('.stars').text(repo.stargazers_count).append(star_icon)

Solution 6 - Javascript

Just in case if you can't change HTML. Very primitive but short & works. (It will empty the parent div hence the child divs will be removed)

$('#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>

Solution 7 - Javascript

I had the same problem but the text was the first node inside the parent element. In this case you can do something like this and it's really quick:

// find the children elements
 termsChildren = $('#one').children()

// replace the text, then re-append the children element.
 $('#one').text(' "Hi I am replace" ').append(termsChildren)

Otherwise, you have to specify which children have to go before the text, and which afterwards:


// find the children elements
 termsChildren = $('#one').children()

// remove all the content
 $('#one').text(' ')
// append the first child element
 $('#one').append(termsChildren[0])
// add the new text and then the other children
 $('#one').text(' "Hi I am replace" ').append(termsChildren.slice(1))

Solution 8 - Javascript

When you replace the plain text of an element with jQuery, you cannot put the plain text on its own, or else it will clear and/or replace the entire element. You should put all the plain text inside a <span> element:

$(document).ready(function() {
  $("#change-btn").click(function() {
    $("#one").children("span").text("Hi I am replace");
  });
});

<!-- Import CSS -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<!-- Import JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>

<div class="m-2">
  <div id="one">
    <div class="first"></div>
    <span>Hi I am text</span>
    <div class="second"></div>
    <div class="third"></div>
  </div>
  <button type="button" class="btn btn-primary btn-sm mt-2" id="change-btn">Click to change text</button>
</div>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmanojadamsView Question on Stackoverflow
Solution 1 - JavascriptBrian UstasView Answer on Stackoverflow
Solution 2 - JavascriptJamiecView Answer on Stackoverflow
Solution 3 - JavascriptgcochardView Answer on Stackoverflow
Solution 4 - JavascriptMusaView Answer on Stackoverflow
Solution 5 - Javascriptonmyway133View Answer on Stackoverflow
Solution 6 - JavascriptReturnTableView Answer on Stackoverflow
Solution 7 - Javascriptaeron13View Answer on Stackoverflow
Solution 8 - JavascriptmrwolferincView Answer on Stackoverflow