Skip to content
Related Articles

Related Articles

HTML | DOM ParentNode.prepend() Method
  • Last Updated : 27 May, 2020

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.




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

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.




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

Output:

In console, you can see textContent of parent element.

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :