Categories
JavaScript Answers

How to Set a DOM element as the First Child?

Spread the love

Sometimes, we may want to set a DOM element as the first child element.

In this article, we’ll look at ways to set a DOM element as the first child.

Using the prepend Method

In modern browsers, an HTML element object comes with the prepend method to let us prepend an element as the first child.

For instance, if we have the following HTML:

<div>  
  <p>  
    bar  
  </p>  
  <p>  
    baz  
  </p>  
</div>

Then we can write the following JavaScript to prepend an element as the first child of the div:

const div = document.querySelector('div')  
const newChild = document.createElement('p')  
newChild.textContent = 'foo'  
div.prepend(newChild)

We get the div with the document.querySelector method.

Then we call document.createElement to create an element.

Next, we set the textContent property to add some content to the p element we created.

And then we call div.prepend to prepend newChild as the first child of the div.

There’s also the append method to append an element as the last child of a parent element.

Using the insertAdjacentElement Method

We can also use the insertAdjacentElement method to insert an element as the first child of an element.

For instance, if we have the same HTML:

<div>  
  <p>  
    bar  
  </p>  
  <p>  
    baz  
  </p>  
</div>

Then we can write:

const div = document.querySelector('div')  
const newChild = document.createElement('p')  
newChild.textContent = 'foo'  
div.insertAdjacentElement('afterbegin', newChild)

to call insertAdjacentElement with 'afterbegin' and the newChild to prepend newChild as the first child element of the div.

Other possible values for the first argument of insertAdjacentElement is:

  • beforebegin: before the element itself.
  • beforeend: just inside the element, after its last child.
  • afterend: after the element itself.

Using the insertBefore Method

Another method we can use to prepend an element as the first child is to use the insertBefore method.

For instance, we can write:

const div = document.querySelector('div')  
const newChild = document.createElement('p')  
newChild.textContent = 'foo'  
if (div.firstChild) {  
  div.insertBefore(newChild, div.firstChild);  
} else {  
  div.appendChild(childNode);  
}

given the same HTML we have in the previous examples to prepend newChild as the first child of the div.

We check if there’s a firstChild element attached to the div.

If there is, then we call insertBefore to insert newChild before the firstChild of the div.

Otherwise, we just call appendChild to append newChild as a child element.

Conclusion

We can use various HTML element methods to prepend an element as the first child of a parent element.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *