Reputation: 1186
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?
Upvotes: 0
Views: 154
Reputation: 7268
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.
Upvotes: 0
Reputation: 655499
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);
Upvotes: 1
Reputation: 944020
document.body.insertBefore(
newNode,
document.getElementById('d2')
);
Upvotes: 2