如何在不使用库的情况下在JavaScript中的另一个元素之后插入元素? [英] How to insert an element after another element in JavaScript without using a library?

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

问题描述

在JavaScript中有 insertBefore(),但如何在不使用jQuery或其他库的情况下在另一个元素之后插入元素

There's insertBefore() in JavaScript, but how can I insert an element after another element without using jQuery or another 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中的另一个元素之后插入元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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