Open In App

HTML DOM ParentNode.prepend() Method

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: 

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.




<!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.




<!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.


Article Tags :