如何在JavaScript中插入After()而不使用库? [英] How to do insert After() in JavaScript without using a library?

查看:110
本文介绍了如何在JavaScript中插入After()而不使用库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中有 insertBefore(),但是如何在不使用jQuery或其他库的情况下插入元素?

There's insertBefore() in JavaScript, but how to do insert after a element without using jQuery or other library?

推荐答案

referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);

其中 referenceNode 是您要的节点在 newNode 之后。如果 referenceNode 是其父元素中的最后一个子元素,那很好,因为 referenceNode.nextSibling null insertBefore 通过添加到列表的末尾来处理这种情况。

Where referenceNode is the node you want to put newNode after. If referenceNode is the last child within its parent element, that's fine, because referenceNode.nextSibling will be null and insertBefore handles that case by adding to the end of the list.

所以:

function insertAfter(newNode, referenceNode) {
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

在此尝试。

这篇关于如何在JavaScript中插入After()而不使用库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆