美文网首页JavaScript学习笔记
原生JS向后添加兄弟元素

原生JS向后添加兄弟元素

作者: last_edc | 来源:发表于2016-12-06 17:17 被阅读1520次

1.实现函数

function insertAfter(newNode,curNode){
    curNode.parentNode.insertBefore(newNode,curNode.nextElementSibling);
}

当前元素为最后一个元素时,nextElementSibling为null,insertBefore会在父元素的最后添加新元素,仍旧生效。

2.nextSibling和nextElementSibling的区别

<div>
    <p id="first">元素1</p>
    节点2
    <p>元素3</p>
</div>

first的nextSibling是“节点2”,nextElementSibling是<p>元素3</p>

相关文章

网友评论

    本文标题:原生JS向后添加兄弟元素

    本文链接:https://www.haomeiwen.com/subject/buurmttx.html