insertBefore method takes two arguments. The first is the element we want to insert, and the second is the element that we want our target to be before. If that sounds confusing, let’s break it down like this:
- Let’s fetch an element called
sectionthat exists in our DOM already.
- Let’s create a new element called
span, that we want to insert inside
- We want the position of span to be before anything else inside
firstChild will allow us to target the first child element inside an element, so we’ll use this in our second parameter for
insertBefore. Here’s what our final code will look like:
// fetch our section element var section = document.querySelector("section"); // create our span element var span = document.createElement("span"); // prepend our span eleemnt to our section element section.insertBefore( span, section.firstChild );
This snippet is a great example of not overcomplicating things when we need to achieve a certain goal. A little thought and usage of what’s already available to us lets us achieve anything we need to.