Javascript在元素后附加Child [英] Javascript Append Child AFTER Element

查看:173
本文介绍了Javascript在元素后附加Child的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个ul元素中使用javascript追加一个li元素,这是我到目前为止的代码..

I would like to append an li element after another li inside a ul element using javascript, This is the code I have so far..

var parentGuest = document.getElementById("one");
var childGuest = document.createElement("li");
childGuest.id = "two";

我熟悉appendChild,

I am familiar with appendChild,

parentGuest.appendChild(childGuest);

然而,这会将新元素追加到另一个元素中,而不是之后。如何在现有元素之后附加新元素?谢谢。

However this appends the new element inside the other, and not after. How can I append the new element after the existing one? Thanks.

<ul>
  <li id="one"><!-- where the new li is being put --></li>
  <!-- where I want the new li -->
</ul>


推荐答案

您可以使用:

if (parentGuest.nextSibling) {
  parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);
}
else {
  parentGuest.parentNode.appendChild(childGuest);
}






但正如帕维尔指出的那样, referenceElement 可以为null / undefined,如果是,则 insertBefore 表现得像 appendChild 。所以以下内容相当于上述内容:


But as Pavel pointed out, the referenceElement can be null/undefined, and if so, insertBefore behaves just like appendChild. So the following is equivalent to the above:

parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);

这篇关于Javascript在元素后附加Child的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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