append vs appendTo in jQuery

append() and appendTo() methods do the same task. Both methods add the content to the end of existing content. However I prefer append(), because it might make the code more readable.

The main difference is way to write the code. With append() method target element come first and source element come in last, but in appendTo() method source element come first and target come last of the code.

append()

$('#container').append('<p>Hi, I am added by append.</p>');

appendTo()

$('<p>Hi, I am added by appendTo.</p>').appendTo($('#container'));

See the Pen Untitled by Nirbhay (@nirbhaysingh) on CodePen.


So, the key difference between append() and appendTo() is that append() adds the specified content to the selected element(s), while appendTo() adds the specified content to the element(s) specified before the method.

No comments :

Please Give Your Feedback