RyBolt RyBolt - 3 months ago 7
jQuery Question

Replace only text contents of html element with jQuery

Here is the test case:

<span id='loading' class="pad"> <i class="fa fa-spinner fa-pulse fa-lg fa-fw"></i> Loading map... </span>


I am trying to dynamically ( via jQuery ) , change only the "Loading map..." portion of this markup. I realize I can rebuild the whole inner contents every time , incorporating and replacing
<i .... {new message here} ... </i>
but I am curious to know if there is a supported api method for this.

I thought $('#loading').text('new message') would work but it removes the
<i>
tag.

Answer

You can use get the object of text node and set the content using textContent:

$('#loading').contents().last()[0].textContent='new message';

$('#loading').contents().last()[0].textContent='new message';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='loading' class="pad"> <i class="fa fa-spinner fa-pulse fa-lg fa-fw"></i> Loading map... </span>