EN
JavaScript - set DOM element as first child
0
points
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>