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, child Node is set at 0th index of Node Object List.

Syntax:

ParentNode.prepend( ChildNodesToPrepend );

Parameters: 

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

Return Value: This method returns undefined.

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 the Child1 and Child2 to parentNode.

In console we had shown childNodes of parentNode.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

In console, you can see textContent of parent element.

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.