1. Computing

JavaScript By Example

Document Object Model: 22. Add Before The Current Node

By

When we are constructing a combination of new nodes to add into the web page we can easily make sure that we add all of our child nodes in the order that we want them to appear in the page. We can't do this if child nodes that need to come after the new nodes already exist in the web page.

The solution to this is to not use the appendChild method to add the new node into the page but to instead use the insertBefore method. This method needs to be attached to the same parent node as we'd use for appendChild but instead of just specifying the new node to add to the end we need to specify both the new node and the existing node that we want to insert before.

Since we need the node we are inserting before anyway it makes sense to start from that one in the web page since we can easily obtain its parent node (which is the one both nodes will be children of). This helps avoid the possible error that would arise if the node to insert before wasn't in fact a child of the one we are running the method on.

HTML


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>Example D22</title>
</head>
<body>
<div><p id="bf">New paragraph to be added before this one.</p></div>
<script type="text/javascript" src="exampleD22.js"></script>
</body>
</html>

JavaScript


var exP, newP;
newP = document.createElement("p");
newP.id = 'new'; exP = document.getElementById('bf');
exP.parentNode.insertBefore(newP,exP);

  1. About.com
  2. Computing
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. Document Object Model
  7. JavaScript By Example - DOM: Add Before The Current Node

©2014 About.com. All rights reserved.