最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript : How to add a nodeelement to a specific-indexed location? - Stack Overflow

programmeradmin6浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 4

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)

  1. 暂无评论