When you want to add element(s) onto the DOM, one way you go about this is to use jQuery’s DOM manipulation methods. The methods .append() and .appendTo() are a bit tricky and confusing at first because they perform the same function. However, the methods differ in purpose.
The .append() method allows you to insert an element into the content, which would be your container that holds all your HTML elements. The new element will be added to the end of each element that matches the selected element. So, the new element that you want to add will be the last child (node) in your collection of matched elements.
An easy way to remember this is .append(‘existingContainer’)
- you are adding a new element to an existing container.
$('newElementToAdd').append(‘existingContainer’)
In contrast, if you want to add elements to the beginning of targeted elements instead of the end, you can use the .prepend() method.
$('newElementToAdd').prepend(‘existingContainer’)
The .appendTo() method works reversely. It allows you to take an existing container and add a new element to it.
You can remember this by .appendTo(‘selector’)
- you are adding an existing container to a new element.
$(‘container’).appendTo(‘newElementToAdd’)
For me, it helps to vocalize the methods to confirm what I’m adding to the DOM. For .append(), “I am adding this to…” and for .appendTo(), “take this and add it to…”.
Check out the documentation for more clarification: .append() and .appendTo().