how to use JavaScript Dom Node insertBefore

In this article I have described about Dom Node insertBefore() method in JavaScript
  • 1493

JavaScript Dom Node insertBefore() method

  • As we already know that node object is used to represent and add node within the HTML document.
  • The insertBefore() method is used to insert a new child node just right to existing node and can also be used to insert or move to an existing node or an element.

Browser support

Following are the main browsers which support the insertBefore() method of Dom Node object

  • Internet Explorer.
  • Firefox.
  • Opera.
  • Google Chrome.
  • Safari.

Syntax

The insertBefore() of Dom Node object has following syntax

node.insertBefore(newnode,existingnode)

Lets take an example

<!DOCTYPE html>

<html>

<body style ="background-color:yellow">

<ul id="myList"><li>AMAN</li><li>NITIN</li></ul>

<p id="MENU">INSERT ITEM TO THE LIST</p>

<button onclick="myFunction()">INSERT</button>

<script type="text/javascript">

    function myFunction() {

        var newItem = document.createElement("LI")

        var textnode = document.createTextNode("ROHIT")

        newItem.appendChild(textnode)

        var list = document.getElementById("myList")

        list.insertBefore(newItem, list.childNodes[0]);

    }

</script>

</body>

</html>

 

Output

 

 DN INSERT1.jpg


When we click on button


DN INSERT2.jpg

Further Readings

You may also want to read these related articles :here

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

Categories

More Articles

© 2013 dotNetheaven. All rights reserved.