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

javascript - How to appendChild as third child - Stack Overflow

programmeradmin2浏览0评论

I want to add a new child node, after a specified node, as the third child node.

<ul id="menu">
    <li>one</li>
    <li>tow</li>
    <li>three</li>
    <li>four</li>
</ul>

<script>
var li = document.createElement("li");
document.getElementById("menu").appendChild(li);
var sometext = document.createTextNode("third one");
li.appendChild(sometext); 
</script>

I want to add a new child node, after a specified node, as the third child node.

<ul id="menu">
    <li>one</li>
    <li>tow</li>
    <li>three</li>
    <li>four</li>
</ul>

<script>
var li = document.createElement("li");
document.getElementById("menu").appendChild(li);
var sometext = document.createTextNode("third one");
li.appendChild(sometext); 
</script>
Share Improve this question edited Nov 11, 2012 at 9:16 Alvin Wong 12.4k5 gold badges54 silver badges78 bronze badges asked Nov 11, 2012 at 9:04 JS-HeroJS-Hero 3171 gold badge7 silver badges18 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

Use insertBefore if you want to add a node anywhere before the end of its container.

parentElement.insertBefore(newNode, currentThirdNode);

keep in mind that there is a difference in childNodes, namely siblings and ElementSiblings. a textNode is a Node, but not an Element. so if you want to insert an element into the the DOM, use nextElementSibling | previousElementSibling and appendChild | insertBefore and the parent's children attribute that only contains Elements like this:

function insertAsThird( element, parent ){
  if ( parent.children.length > 2 ){
   parent.insertBefore(element, parent.children[2]);
 }
 else parent.appendChild(element);
}

and use it like this:

insertAsThird( yourThirdElement, document.getElementById("your target parent"));

if you want to to work on childNodes, not Elements, just change the parent.children parts to parent.childNodes

I think you should append the textNode before adding the new element like this:

<script>
  var li = document.createElement("LI");
  var sometext = document.createTextNode("third one");
  li.appendChild(sometext);

  var menu = document.getElementById("menu");
  var third = parent.getElementsByTagName("LI")[2];

  menu.insertBefore(li, third);
</script>

I Hope this works for you..

javascript (without jQuery):

var newLi = document.createElement("li");
newLi.innerHTML ="new el 3"
var menu = document.getElementById("menu");
var el3 = menu.getElementsByTagName("li")[2];
menu.insertBefore(newLi, el3);

or with jQuery:

$('#menu').children().eq(1).append('<li>new</li>');    
发布评论

评论列表(0)

  1. 暂无评论