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.
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'); 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/
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')); 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"'; 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.
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) 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)