HTML and CSS Reference
In-Depth Information
15.7.4 Inserting Before a Node
The insertBefore() method allows you to insert a child node before the specified node,
called the reference node, and if the reference node is null, this will insert the node at
the end of a list of child nodes.
FORMAT
insertBefore(newElement, targetElement)
EXAMPLE
document.body.insertBefore(newPara, firstPara);
Example 15.8 demonstrates how to insert a new paragraph node into a DOM before
another node.
EXAMPLE 15.8
<html>
<head><title>Inserting Before</title>
<style type="text/css">
p { font-style:arial;
color:darkblue;
font-size:18;
}
</style>
<script type="text/javascript">
1
function insertMessage() {
2
var newPara = document.createElement("p");
3
var newText = document.createTextNode("I am inserting
myself above you!");
// If you copy this, don't break the lines .
4
newPara.appendChild(newText);
5
var firstPara = document.getElementById("firstp");
6
document.body.insertBefore(newPara, firstPara);
}
</script>
</head>
7
<body onload="insertMessage() ">
< p id=”firstp” >I was supposed to be first.</p>
</body>
</html>
EXPLANATION
1
Once the page has loaded, this function will be called.
2
With the createElement() method, a new paragraph is created. A reference to it is
assigned to a variable, newPara .
 
 
Search WWH ::




Custom Search