Add span/html element after text node using JQuery

Viewed 67

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

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