您的位置:首页 > 移动开发

js:appendChild、insertBefore和insertAfter

2017-02-20 15:12 309 查看


转自:http://www.cnblogs.com/mybkn/archive/2013/04/09/3011061.html


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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: