Append Vs. Prepend. What’s The Difference?
We will start with Prepend.
Let’s say you have a div that is acting as a container. And in this container you already have existing elements. Here in our example, we have a div with an h2 tag inside of it with the words “eat”.
The goal is to use JS to manipulate this div and add an additional element to it WITHOUT removing the existing elements. And we specifically want to add this new element BEFORE the other elements currently in the div, which is the h2 tag.
This is where prepend comes into play.
First thing is to create a variable called “bear”. This variable will hold an image tag for us. Next, we can grab the div tag by its id or class name using our JQuery selector function $() and attach the prepend function. The prepend function will take the variable “bear” as an argument.
And viola, we have an image of a bear! But notice that the bear is placed BEFORE the h2 tag. The prepend function will add something to the beginning without removing what’s already there! Pretty cool huh? 😎
Now, let’s talk about Append!
Well, append works the exact same way only it will add something to the end. To demonstrate this, we will create another variable and call it “beet”. This variable will also hold an image tag for us. In the same fashion, we will grab the div tag by its id or class name using our JQuery selector function $() and attach the append function. The append function will take the variable “beet” as an argument.
And there you have it! Underneath the h2 tag we have an image of a beet thanks to the append function. The image was placed AFTER it. The append function will add something to the end without removing what’s already inside!
I hope you found this helpful and be on the look out for more blogs/vlogs next week. Until then….Happy coding Ya’ll 😜!