insertBefore()
The insertBefore() method accepts two arguments:
- the node to insert
- a reference node.
The node to insert becomes the previous sibling of the reference node and is returned by the method. If the reference node is null, then insertBefore() acts the same as appendChild():
insert as last child
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<div id="div1">
<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ul>
</div>
<p id="p1">Hello <b>World!</b></p>
<script type="text/javascript">
var div = document.getElementById("div1");
var p = document.getElementById("p1");
//insert as last child
var returnedNode = div.insertBefore(p, null);
document.writeln(p == div.lastChild); //true
</script>
</body>
</html>
Insert as the new first child
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<div id="div1">
<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ul>
</div>
<p id="p1">Hello <b>World!</b></p>
<script type="text/javascript">
var div = document.getElementById("div1");
var p = document.getElementById("p1");
//insert as the new first child
var returnedNode = div.insertBefore(p, div.firstChild);
document.writeln(returnedNode == p); //true
document.writeln(p == div.firstChild); //true
</script>
</body>
</html>
Insert before last child
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<div id="div1">
<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ul>
</div>
<p id="p1">Hello <b>World!</b></p>
<script type="text/javascript">
var div = document.getElementById("div1");
var p = document.getElementById("p1");
//insert before last child
var returnedNode = div.insertBefore(p, div.lastChild);
document.writeln(p == div.childNodes[div.childNodes.length-2]); //true
</script>
</body>
</html>
Home
JavaScript Book
DOM
JavaScript Book
DOM
DOM Model:
- Document Object Model
- nodeName and nodeValue Properties
- Node Relationships:childNodes
- parentNode
- previousSibling and nextSibling properties
- lastChild and firstChild
- appendChild() adds a node to the end of the childNodes list
- insertBefore()
- ownerDocument property
- removeChild
- replaceChild()
- Working with Text
- Check the length of NodeList
- Convert NodeList to an Array
- html tag and its cooresponding JavaScript class