I have an element("p") which has say 10 children(10 div's).Based on user request i want to add a div under the "p" element to say 5th or 2ed position in the "p" Dom tree.
var div = document.createElement("div"); //Comment Append
div.id="div"+divId;
div.className="div";
div.appendChild(document.createTextNode(divText));
var p = document.getElementById("ment");
length=p.childNodes.length;
Say p has a length of 15 and i want to add the div to the 13th position(adding it and NOT replacing it -- not replaceChild)
If i try traversing to the 13th position and do a parentNode.appendChild
it gets appended(obviously) to the last position(15th position will be the new Div)
i want to add a div or any element to an Indexed location in a child list.
Please help.
I have an element("p") which has say 10 children(10 div's).Based on user request i want to add a div under the "p" element to say 5th or 2ed position in the "p" Dom tree.
var div = document.createElement("div"); //Comment Append
div.id="div"+divId;
div.className="div";
div.appendChild(document.createTextNode(divText));
var p = document.getElementById("ment");
length=p.childNodes.length;
Say p has a length of 15 and i want to add the div to the 13th position(adding it and NOT replacing it -- not replaceChild)
If i try traversing to the 13th position and do a parentNode.appendChild
it gets appended(obviously) to the last position(15th position will be the new Div)
i want to add a div or any element to an Indexed location in a child list.
Please help.
Share Improve this question asked Jul 28, 2011 at 10:30 Vivek ChandraVivek Chandra 4,3569 gold badges35 silver badges39 bronze badges2 Answers
Reset to default 4You're looking for insertBefore
Try insertBefore
.
elementNode.insertBefore(new_node,existing_node)
The insertBefore() method inserts a new child node before an existing child node.