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.
In this example, we use insertBefore()
method to set the newFirstChild
element to be the first child of the body
element.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="first">first child of the body</div>
5
<script>
6
7
var element = document.querySelector('#first');
8
9
var newFirstChild = document.createElement('div');
10
11
newFirstChild.textContent = 'new first child';
12
13
element.insertBefore(newFirstChild, element.firstChild); // sets newFirstChild as first child
14
15
</script>
16
</body>
17
</html>
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
.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="container">
5
<div id="first">first child of the container</div>
6
</div>
7
<script>
8
9
var container = document.querySelector('#container');
10
11
var firstChild = container.firstChild;
12
13
var newFirstChild = document.createElement('div');
14
15
newFirstChild.textContent = 'new first child';
16
17
container.insertBefore(newFirstChild, firstChild); // sets newFirstChild as first child
18
19
</script>
20
</body>
21
</html>