Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add span/html element after text node using JQuery

Tags:

html

jquery

I have this example

$('span.first').append('<span class="second">2</span>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="first">1</span> HELLO

I get this output: 12 HELLO

I need this output: 1 HELLO 2

like image 644
Michal AB Avatar asked May 07 '26 13:05

Michal AB


1 Answers

Your code was putting the 2 as a child to the span element hence why it was displaying as 12. For the result you are after, simply append to the parent of that element instead:

$('span.first').parent().append('<span class="second">2</span>');
like image 83
A Paul Avatar answered May 09 '26 02:05

A Paul