Hello Hello Hello

Jquery after() method removing DOM element

301 Views Asked by At

The Jquery after() method is used to insert HTML element after the selected elements. My code is

  <h2>Greetings</h2>
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
  </div>

Jquery Code:

$( ".inner" ).after( "<h2>Greetings</h2>" );

The above code working fine. The Jquery is inserting <h2>Greetings</h2> code after two div tags. The HTML generating like below

<div class="container">
  <h2>Greetings</h2>
  <div class="inner">Hello</div>
  <h2>Greetings</h2>
  <div class="inner">Goodbye</div>
  <h2>Greetings</h2>
</div>

But when i pass Jquery selector $('h2') as a parameter to after() method like below

$( ".inner" ).after( $('h2') );

Jquery removes the first original <h2>Greetings</h2> tag and after it inserts <h2>Greetings</h2> tag after two div tags. The HTML generating like below.

<div class="container">
  <div class="inner">Hello</div>
  <h2>Greetings</h2>
  <div class="inner">Goodbye</div>
  <h2>Greetings</h2>
</div>

What is the difference when pass Jquery DOM selector and plain HTML tag.

2

There are 2 best solutions below

2
adeneo On

When you use a string, jQuery creates the neccessary elements based on the string of HTML passed in, so

$("<h2>Greetings</h2>")

actually creates a new H2 element, while

$('h2')

selects all H2 elements in the document.

As after() does something like

 $.fn.after = function(arg) {
     return this.each(function() { // loops over all .inner elements

         var elem = $(arg); // "h2" selects all H2, "<h2>" creates H2 elements
         this.parentNode.insertBefore(elem, this.nextSibling); // something like that,
     });                                                       // not really important ?
 }

..it either creates a new H2 ($("<h2>")) for every matching element found in $( ".inner" ), because of the each loop, or it just moves the same elements from $('h2') to after each .inner, meaning the selected H2 elements will end up after the last .inner

When you use a selector, you select the existing H2 element that is on the page, and move them

var h2 = $('h2'); // selects all H2 elements on the page

$( ".inner" ).after( h2 ); // moves those elements after .inner
0
Elheni Mokhles On

When you use $("selector") you're referencing the DOM element, in your example you're selecting the "h2" element.

So when you append it to another element or using after(), you're taking the element itself and move it to its new place.

You can use JQuery clone function to clone the selected element

var clonedH2 = $("h2").clone()
$("selector").after(clonedH2)