manoj manoj - 6 months ago 34
Javascript Question

Replace only text inside a 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 "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.

Answer

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