Replace only text inside a div using jquery
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>
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');