在JavaScript中有insertBefore(),但如何在不使用jQuery或其他库的情况下在另一个元素之后插入一个元素?
当前回答
我使用以下命令在选择的末尾插入选项。通过传递null作为第二个参数。我不确定这是否是一个异常的“选择”元素,因为我从来没有尝试过其他任何东西,但如果有人来这里寻找这个可能会有所帮助。在IE上也能工作(令人惊讶)。:)
var x = document.getElementById("SELECT_LIST");
var boption = document.createElement("option");
boption.text = "SOME TEXT";
boption.value = "SOME VALUE";
x.insertBefore(boption, null);
其他回答
输入随身的“强暴”
elementBefore.insertAdjacentHTML('afterEnd', elementAfter.outerHTML)
好处:
烘干机:你不需要将before节点存储在变量中并使用它两次。如果重命名变量,就少发生修改。 golfs比insertBefore更好(如果现有的节点变量名是3个字符长,则打破平衡)
缺点:
较低的浏览器支持,因为更新:https://caniuse.com/#feat=insert-adjacent 将丢失元素的属性,例如事件,因为outerHTML将元素转换为字符串。我们需要它是因为insertAdjacentHTML从字符串而不是元素中添加内容。
快速搜索谷歌会显示这个脚本
// create function, it expects 2 values.
function insertAfter(newElement,targetElement) {
// target is what you want it to go after. Look for this elements parent.
var parent = targetElement.parentNode;
// if the parents lastchild is the targetElement...
if (parent.lastChild == targetElement) {
// add the newElement after the target element.
parent.appendChild(newElement);
} else {
// else the target has siblings, insert the new element between the target and it's next sibling.
parent.insertBefore(newElement, targetElement.nextSibling);
}
}
可以使用appendChild函数在元素之后插入。
参考:http://www.w3schools.com/jsref/met_node_appendchild.asp
我使用以下命令在选择的末尾插入选项。通过传递null作为第二个参数。我不确定这是否是一个异常的“选择”元素,因为我从来没有尝试过其他任何东西,但如果有人来这里寻找这个可能会有所帮助。在IE上也能工作(令人惊讶)。:)
var x = document.getElementById("SELECT_LIST");
var boption = document.createElement("option");
boption.text = "SOME TEXT";
boption.value = "SOME VALUE";
x.insertBefore(boption, null);
这是使用普通javascript在另一个元素之后添加一个元素的最简单方法
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
参考: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML