Open In App

HTML DOM ParentNode.prepend() Method

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

The ParentNode.prepend() method inserts a set of Node objects or DOMString objects before the first child of the ParentNode. Hence, the child Node is set at the 0th index of the Node Object List.

Syntax:

ParentNode.prepend( ChildNodesToPrepend );

Parameters: 

  • ChildNodesToPrepend: Child nodes to prepend act as Parameters for this method.
  • prepend text: We can prepend text also.

Return Value: This method returns undefined.

The below examples illustrate the ParentNode.prepend() method:

Example 1: Prepending an element. To show this method, we have created three elements parentNode, Child1 and Child2. Then we prepended Child1 and Child2 to parentNode.In the console, we had shown childNodes of parentNode.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <title>Prepend</title>
</head>
 
<body>
    <h1>GeeksforGeeks</h1>
 
    <script>
        let parentNode = document.createElement("div");
        let Child1 = document.createElement("p");
        let Child2 = document.createElement("div");
        parentNode.prepend(Child1);
        parentNode.prepend(Child2);
        console.log(parentNode.childNodes);
    </script>
</body>
 
</html>


Output: In the console, you can see the childNodeList of parentNode.One is div and one is p

 

Example 2:Prepending text. In this example, we have prepended some text to the innerHTML of the element and the element’s textContent.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <title>Prepend</title>
</head>
 
<body>
    <h1>GeeksforGeeks</h1>
 
    <script>
        let parent = document.createElement("div");
        parent.innerHTML =
            "A Computer Science Portal for Geeks";
        parent.prepend("GeeksforGeeks : ");
        console.log(parent.textContent);
    </script>
</body>
 
</html>


Output: In the console, you can see the textContent of the parent element.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads