131

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.

2
  • It might be helpful to make a fiddle
    – Inkbug
    Aug 8, 2012 at 14:56
  • 1
    Use $('#one').find('.first').text('Hi I am replace'); instead of $('#one').text(); or you can directly access the element and replace text by using $('.first').text('Hi I am replace'); Jul 3, 2017 at 8:41

8 Answers 8

154

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');
3
  • 72
    This doesn't answer the OP's question, who did not say that they have control over the HTML.
    – tar
    Jun 24, 2016 at 16:47
  • 1
    this is worked but how can sure to executed or not ? can i run exception if blank or tag changed? in unsuccessful bindings because this div created by code.from REST or database May 1, 2017 at 7:07
  • this is wrong. .text will tail the text to existing one.
    – sam kh
    Jan 30, 2022 at 15:45
150

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>

7
  • 9
    This should be the accepted answer since this doesn't require you to change the html! Sep 2, 2016 at 9:48
  • 2
    @Jamiec FWIW I love this answer because it allows replacements without worrying about borking the markup/scripts etc.
    – sehe
    Nov 2, 2016 at 12:02
  • 3
    This worked perfectly for me. Sometimes we work in situations that don't allow changing the HTML (ie SharePoint). Thanks
    – Mark P.
    Aug 28, 2017 at 19:39
  • Why not replace 3 with Node.TEXT_NODE to make the snippet clearer?
    – Paul
    Oct 13, 2020 at 13:51
  • 1
    @Paul thanks, it is much clearer so I've included it as a note on this old answer.
    – Jamiec
    Oct 13, 2020 at 13:56
20

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'));
1
  • While this would work in this case, I do not like this option because if you were replacing the word "first" with the word "second" or just 'i' with '' it would mess up your tags
    – JSON
    Sep 20, 2017 at 2:03
11

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/

1
  • 2
    From jQuery 1.8.3 $('#one').contents(':not(*)') will select nothing.
    – BruceHill
    May 2, 2014 at 17:43
1

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>

2
  • 2
    This removes all of the child divs of #one
    – Scot Nery
    Jul 12, 2019 at 1:48
  • 1
    @ScotNery thank you, I have updated the answer. (Although it technically answers this particular question) I'm assuming other than wrapping the text with a tag that has an id, it'd be quite challenging. Only other thing is to match a string to replace, but it's really fragile. Jul 12, 2019 at 2:00
0

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

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

-1

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.