Open In App

How to set DOM Element as First Child ?

Last Updated : 21 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will explore different approaches to setting a DOM element as the first child of its parent. When working with HTML documents, it is common to manipulate the DOM (Document Object Model) to rearrange elements dynamically, Setting a DOM element as the first child means inserting it at the beginning of its parent’s list of children elements.

There are several methods that can be used to set the DOM element as the first child.

We will explore all the above methods along with their basic implementation with the help of examples.

Approach 1: Using insertBefore()

In this approach we are using the insertBefore() method, the insertBefore() method in HTML DOM is used to insert a new node before the existing node as specified by the user.

Syntax:

parentElement.insertBefore(newChild, parentElement.firstChild);

Example: In this example, we use the insertBefore() method to insert the newly created paragraph element (newChild) as the first child of the parent (parentElement).

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>Set DOM Element as First Child</title>
</head>
  
<body>
    <div id="parent">
        <p>Existing Child 1</p>
        <p>Existing Child 2</p>
    </div>
  
    <script>
        const parentElement =
            document.getElementById("parent");
        const newChild =
            document.createElement("p");
        newChild.textContent = "New First Child";
  
        parentElement.insertBefore(
            newChild, parentElement.firstChild);
    </script>
</body>
  
</html>


Output:

12

Approach 2: Using prepend()

In this approach we are using the jQuery prepend() method, the prepend() method is an inbuilt method in jQuery that is used to insert specified content at the beginning of the selected element.

Syntax:

$(selector).prepend(content, function)

Example: In this example, we utilize jQuery’s prepend() method to directly add the newChild element as the first child of the parent with the ID “parent.”

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>Set DOM Element as First Child</title>
    <script src=
    </script>
</head>
  
<body>
    <div id="parent">
        <p>Existing Child 1</p>
        <p>Existing Child 2</p>
    </div>
  
    <script>
        const newChild = document.createElement("p");
        newChild.textContent = "New First Child";
  
        $(document).ready(function () {
            $("#parent").prepend(newChild);
        });
    </script>
</body>
  
</html>


Output:

12



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads