开发者

javascript : How to add a node/element to a specific-indexed location?

开发者 https://www.devze.com 2023-03-23 07:18 出处:网络
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.

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("comment");
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 开发者_JS百科will be the new Div)

i want to add a div or any element to an Indexed location in a child list.

Please help.


You'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.

0

精彩评论

暂无评论...
验证码 换一张
取 消