views:

43

answers:

3

Suppose I have two DIVs on my page.

<body>
<div id="d1"></div>
<div id="d2"></div>
</body>

I want to create a new DIV dynamically using JavaScript and place it between d1 and d2. If I use the appendChild method the new DIV is placed at the end.

Right now I can only think of paring the innerHTML of the BODY and appending the new DIV at the desired location. Is there a better way?

+2  A: 

insertBefore

document.body.insertBefore( 
    newNode, 
    document.getElementById('d2') 
);
David Dorward
Thank you very much!
Madhu
+1  A: 

There is the Node.insertBefore method to insert a node before another:

var newNode = document.createElement("div"),
    d2 = document.getElementById("d2");
d2.parentNode.insertBefore(newNode, d2);
Gumbo
I should have referred the DOM before asking. :) Thanks!
Madhu
A: 

Hi

For DOM manipulation , jQuery API offers various helpful methods.Following are some of them :-

insertBefore() , insertAfter() , append() , appendTo() , prepend() , prependTo() etc . These functions provide more control over insertion of DOM elements at specific locations in web page.

Pawan Mishra