且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

js:appendChild、insertBefore和insertAfter

更新时间:2022-09-16 10:27:02

web/Win8开发中经常要在js中动态增加一些element,就需要用到下面的一些方法:

appendChild:

target.appendChild(newChild)

newChild作为target的子节点插入最后的一子节点之后

insertBefore:

target.insertBefore(newChild,existingChild)

newChild作为target的子节点插入到existingChild节点之前

existingChild为可选项参数,当为null时其效果与appendChild一样

 

insertAfter: 

顾名思义,就是在node后面增加new node,但是没有现成的API提供调用,但也很容易的自己可以写:

js:appendChild、insertBefore和insertAfter
function insertAfter(newEl, targetEl)
{
    var parentEl = targetEl.parentNode;
            
     if(parentEl.lastChild == targetEl)
     {
           parentEl.appendChild(newEl);
      }else
      {
           parentEl.insertBefore(newEl,targetEl.nextSibling);
       }            
}
js:appendChild、insertBefore和insertAfter

 本文转自老Zhan博客园博客,原文链接:http://www.cnblogs.com/mybkn/archive/2013/04/09/3011061.html,如需转载请自行联系原作者