VAAA VAAA - 14 days ago 7
jQuery Question

jQuery insertAfter a button that is inside div with class

I have the following div:

<div class="alert alert-danger alert-dismissible fade in" style="display:none;">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>


I need to append text and remove it later just after
</button>
tag.

My code is:

$('This is a test').insertAfter('.alert alert-danger > button');


So the expected out should be:

<div class="alert alert-danger alert-dismissible fade in" style="display:none;">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
This is a Test
</div>


But is not working.

And I guess for removing will be something like:

$('.alert alert-danger > button').nextAll().remove();



Any clue?

Answer

Wrap the text in an element and insert that. It will be far easier to remove than parsing through text nodes for which jQuery has no direct methods to access them

$('<span>').text('This is a test').insertAfter('.alert.alert-danger > button');

Now the nextAll().remove() should also work

Note that $('some text') is not valid for $()

Comments