js:appendChild、insertBefore和insertAfter


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提供调用,但也很容易的自己可以写:

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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM