Using the insertBefore() Method
insertBefore() method allows you to insert a new node before an existing node. To set a DOM element as the first child of another element, you can use this method in conjunction with the
<script> // Get the parent element const parent = document.getElementById('parent-element'); // Get the first child of the parent element const firstChild = parent.firstChild; // Create a new element const newElement = document.createElement('div'); // Use insertBefore to set the new element as the first child parent.insertBefore(newElement, firstChild); </script>
In the above example, we first retrieve the parent element using its ID. We then get the first child of the parent element using the
firstChild property. Finally, we create a new element and use
insertBefore() to insert it before the first child.
insertBefore() method and the
firstChild property, you can achieve this in just a few lines of code.