Difference between .append() and .after() function in JQuery


.append(): This function Insert the data or content inside an element at last index. Means it puts the content inside an element (making the content its child) specified by the parameter at the end of element in the set of matched elements.

Whereas ,

.after(): This function puts the element after the specified element. Or you can say that it insert data outside an element (making the content its sibling) in the set of matched elements.


Let's see an example to get difference in pratical:

Suppose you have html code like this.

<div class='a'> //<---you want div c to append in this div at last.
  <div class='b'>b</div>
</div>

Then you should use .append() function like this.

$("div.a").append("<div class='c'>C</div>");

Then, the html code looks like this.

<div class='a'>
  <div class='b'>b</div>
   <div class='c'>C</div> /<----this will be placed here.
</div>

On other hand,

And, if you are using .after() method in the above same html code, then it will add at the last div having class a as it's sibling.

$("div.a").after("<div class='c'>C</div>");

<div class='a'>
  <div class='b'>b</div>
</div>
<div class='c'>C</div> //<----this will be placed here.

So, this will clearly understand from the above that:

The .append insert the parameter element inside the selector element's tag at the last index position,  whereas the .after puts the parameter element after the matched element's tag. 

Ebook Download
View all
Learn
View all