Donato Donato - 7 months ago 7
Javascript Question

Change text of element that contains other elements

I have markup like this:

<li data-id="1">
<button type="button" class="btn btn-default btn-md" style="margin: .25em; padding: .25em;">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
random text
<input type="hidden" name="global_filter[default_fields][][apple]" value="random text_again">
</button>
</li>


I want to change the text "random text" to "something else".

I am able to find the text node:

$li.find('button').first().contents().filter(function() {
return this.nodeType == 3;
}).text();


But how can I change the text? When I pass an argument to text like
text('something else')
, nothing changes.

Answer

I would probably put the text in its own container like

<div id='changeableText'>Random Text</div>

and then just access it directly with

$('#changeableText').text('New text!');

to accomplish this.

Comments