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.
When you use a string, jQuery creates the neccessary elements based on the string of HTML passed in, so
actually creates a new H2 element, while
selects all H2 elements in the document.
As
after()does something like..it either creates a new H2 (
$("<h2>")) for every matching element found in$( ".inner" ), because of theeachloop, or it just moves the same elements from$('h2')to after each.inner, meaning the selected H2 elements will end up after the last.innerWhen you use a selector, you select the existing H2 element that is on the page, and move them