Languages
[Edit]
EN

JavaScript - set DOM element as first child

0 points
Created by:
DEX7RA
580

In this article, we would like to show you how to set the DOM element as the first child using JavaScript.

Practical examples

Example 1 - first child of the body

In this example, we use insertBefore() method to set the newFirstChild element to be the first child of the body element.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div id="first">first child of the body</div>
  <script>

    var element = document.querySelector('#first');
    
    var newFirstChild = document.createElement('div');
    
    newFirstChild.textContent = 'new first child';

    element.insertBefore(newFirstChild, element.firstChild); // sets newFirstChild as first child
    
  </script>
</body>
</html>

Example 2 - working with container

In this example, we use firstChild property to get the first child of the container. Then we use insertBefore() method to set the newFirstChild element to be the first child of the container.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div id="container">
    <div id="first">first child of the container</div>
  </div>
  <script>

    var container = document.querySelector('#container');
    
    var firstChild = container.firstChild;
    
    var newFirstChild = document.createElement('div');

    newFirstChild.textContent = 'new first child';

    container.insertBefore(newFirstChild, firstChild); // sets newFirstChild as first child
    
  </script>
</body>
</html>

 

References

  1. Node.insertBefore() - Web APIs | MDN

Alternative titles

  1. JavaScript - set HTML DOM element as first child
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join