Definition and Usage..
The insertBefore() method inserts a node as a child, right before an existing child, which you specify.
Tip: If you want to create a new list item, with text, remember to create the text as a Text node which you append to the
Syntax: node.insertBefore(newnode, existingnode)
Different way to how to declare insertBefore() Method in program.
<!DOCTYPE html>
<html>
<body>
<ul id="myList">
<li>JAVA</li>
<li>PYTHON</li>
</ul>
<p>Click the button to insert an item to the list.</p>
<button onclick="ADDElmnt()">ADD</button>
<ul id="List1"><li>HTML</li><li>CSS</li></ul>
<ul id="List2"><li>JAVA SCRIPT</li><li>SQL</li></ul>
<button onclick="ADD()">ADD</button>
<script>
function ADDElmnt() {
var newItem = document.createElement("LI");
newItem.innerHTML="C++";
var list = document.getElementById("myList");
list.insertBefore(newItem, list.childNodes[0]);
}
function ADD() {
var node =document.getElementById("List2").lastChild;
//firstChild,childNodes[0]
var list = document.getElementById("List1");
list.insertBefore(node,list.firstChild);//list.childNodes[0],list.lastChild
}
</script>
</body>
</html>
<html>
<body>
<ul id="myList">
<li>JAVA</li>
<li>PYTHON</li>
</ul>
<p>Click the button to insert an item to the list.</p>
<button onclick="ADDElmnt()">ADD</button>
<ul id="List1"><li>HTML</li><li>CSS</li></ul>
<ul id="List2"><li>JAVA SCRIPT</li><li>SQL</li></ul>
<button onclick="ADD()">ADD</button>
<script>
function ADDElmnt() {
var newItem = document.createElement("LI");
newItem.innerHTML="C++";
var list = document.getElementById("myList");
list.insertBefore(newItem, list.childNodes[0]);
}
function ADD() {
var node =document.getElementById("List2").lastChild;
//firstChild,childNodes[0]
var list = document.getElementById("List1");
list.insertBefore(node,list.firstChild);//list.childNodes[0],list.lastChild
}
</script>
</body>
</html>
Comments
Post a Comment