在JavaScript中有insertBefore()
,但是如何在不使用jQuery或其他库的情况下在另一个元素之后插入元素?
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
其中referenceNode
是您想要放置newNode
的节点。如果referenceNode
是其父元素中的最后一个子元素,那很好,因为referenceNode.nextSibling
将是null
,而insertBefore
通过添加到列表的末尾来处理这种情况。
所以:
function insertAfter(newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
理想情况下,insertAfter
应该与insertBefore类似。以下代码将执行以下操作:
Node
Node
,则附加新的Node
Node
之后没有Node
,则附加新的Node
Node
之后有兄弟姐妹,那么新的Node
就会在兄弟姐妹之前插入Node
扩展Node
Node.prototype.insertAfter = function(node, referenceNode) {
if (node)
this.insertBefore(node, referenceNode && referenceNode.nextSibling);
return node;
};
一个常见的例子
node.parentNode.insertAfter(newNode, node);
查看正在运行的代码
// First extend
Node.prototype.insertAfter = function(node, referenceNode) {
if (node)
this.insertBefore(node, referenceNode && referenceNode.nextSibling);
return node;
};
var referenceNode,
newNode;
newNode = document.createElement('li')
newNode.innerText = 'First new item';
newNode.style.color = '#FF0000';
document.getElementById('no-children').insertAfter(newNode);
newNode = document.createElement('li');
newNode.innerText = 'Second new item';
newNode.style.color = '#FF0000';
document.getElementById('no-reference-node').insertAfter(newNode);
referenceNode = document.getElementById('no-sibling-after');
newNode = document.createElement('li');
newNode.innerText = 'Third new item';
newNode.style.color = '#FF0000';
referenceNode.parentNode.insertAfter(newNode, referenceNode);
referenceNode = document.getElementById('sibling-after');
newNode = document.createElement('li');
newNode.innerText = 'Fourth new item';
newNode.style.color = '#FF0000';
referenceNode.parentNode.insertAfter(newNode, referenceNode);
<h5>No children</h5>
<ul id="no-children"></ul>
<h5>No reference node</h5>
<ul id="no-reference-node">
<li>First item</li>
</ul>
<h5>No sibling after</h5>
<ul>
<li id="no-sibling-after">First item</li>
</ul>
<h5>Sibling after</h5>
<ul>
<li id="sibling-after">First item</li>
<li>Third item</li>
</ul>
此代码用于将最后一个现有子项后面的链接项插入inlining一个小的css文件
var raf, cb=function(){
//create newnode
var link=document.createElement('link');
link.rel='stylesheet';link.type='text/css';link.href='css/style.css';
//insert after the lastnode
var nodes=document.getElementsByTagName('link'); //existing nodes
var lastnode=document.getElementsByTagName('link')[nodes.length-1];
lastnode.parentNode.insertBefore(link, lastnode.nextSibling);
};
//check before insert
try {
raf=requestAnimationFrame||
mozRequestAnimationFrame||
webkitRequestAnimationFrame||
msRequestAnimationFrame;
}
catch(err){
raf=false;
}
if (raf)raf(cb); else window.addEventListener('load',cb);
<!DOCTYPE html>
<html lang="ca">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function createDiv(){
var newDiv = document.createElement("div");
var txt = document.createTextNode("I'm the second div");
newDiv.appendChild(txt);
var x = document.getElementsByTagName("BODY")[0];
x.insertBefore(newDiv, third);
}
</script>
</head>
<body>
<div class="first">
<p>
I'm the first div
</p>
</div>
<div id="third">
<p>
I'm the third div
</p>
</div>
<button type= " button " name= " button " onclick = " createDiv() " >
Create the second Div
</button>
</body>
</html>
您可以使用appendChild
函数在元素后插入。
insertAfter的强大实现。
// source: https://github.com/jserz/domPlus/blob/master/src/insertAfter()/insertAfter.js
Node.prototype.insertAfter = Node.prototype.insertAfter || function (newNode, referenceNode) {
function isNode(node) {
return node instanceof Node;
}
if(arguments.length < 2){
throw(new TypeError("Failed to execute 'insertAfter' on 'Node': 2 arguments required, but only "+ arguments.length +" present."));
}
if(isNode(newNode)){
if(referenceNode === null || referenceNode === undefined){
return this.insertBefore(newNode, referenceNode);
}
if(isNode(referenceNode)){
return this.insertBefore(newNode, referenceNode.nextSibling);
}
throw(new TypeError("Failed to execute 'insertAfter' on 'Node': parameter 2 is not of type 'Node'."));
}
throw(new TypeError("Failed to execute 'insertAfter' on 'Node': parameter 1 is not of type 'Node'."));
};
让我们处理所有场景
function insertAfter(newNode, referenceNode) {
if(referenceNode && referenceNode.nextSibling && referenceNode.nextSibling.nodeName == '#text')
referenceNode = referenceNode.nextSibling;
if(!referenceNode)
document.body.appendChild(newNode);
else if(!referenceNode.nextSibling)
document.body.appendChild(newNode);
else
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
if( !Element.prototype.insertAfter ) {
Element.prototype.insertAfter = function(item, reference) {
if( reference.nextSibling )
reference.parentNode.insertBefore(item, reference.nextSibling);
else
reference.parentNode.appendChild(item);
};
}
我知道这个问题已经有太多的答案,但它们都没有达到我的确切要求。
我想要一个与parentNode.insertBefore
具有完全相反的行为的函数 - 也就是说,它必须接受一个空的referenceNode
(accepted answer没有),并且insertBefore
将在孩子的末尾插入,这个必须在开头插入,否则根本无法在起始位置插入此功能;同样的原因insertBefore
插入最后。
由于null referenceNode
要求您找到父对象,我们需要知道父对象 - insertBefore
是parentNode
的一种方法,因此它可以通过这种方式访问父对象;我们的函数没有,所以我们需要传递父作为参数。
结果函数如下所示:
function insertAfter(parentNode, newNode, referenceNode) {
parentNode.insertBefore(
newNode,
referenceNode ? referenceNode.nextSibling : parentNode.firstChild
);
}
或者(如果你必须,我不推荐它)你当然可以增强Node
原型:
if (! Node.prototype.insertAfter) {
Node.prototype.insertAfter = function(newNode, referenceNode) {
this.insertBefore(
newNode,
referenceNode ? referenceNode.nextSibling : this.firstChild
);
};
}
追加之前:
element.parentNode.insertBefore(newElement, element);
追加后:
element.parentNode.insertBefore(newElement, element.nextSibling);
通过构建以下原型,您将能够直接从新创建的元素中调用这些函数。
newElement.appendBefore(element);
newElement.appendAfter(element);
.append之前(元素)原型
Element.prototype.appendBefore = function (element) {
element.parentNode.insertBefore(this, element);
},false;
.appendAfter(element)原型
Element.prototype.appendAfter = function (element) {
element.parentNode.insertBefore(this, element.nextSibling);
},false;
/* Adds Element BEFORE NeighborElement */
Element.prototype.appendBefore = function(element) {
element.parentNode.insertBefore(this, element);
}, false;
/* Adds Element AFTER NeighborElement */
Element.prototype.appendAfter = function(element) {
element.parentNode.insertBefore(this, element.nextSibling);
}, false;
/* Typical Creation and Setup A New Orphaned Element Object */
var NewElement = document.createElement('div');
NewElement.innerHTML = 'New Element';
NewElement.id = 'NewElement';
/* Add NewElement BEFORE -OR- AFTER Using the Aforementioned Prototypes */
NewElement.appendAfter(document.getElementById('Neighbor2'));
div {
text-align: center;
}
#Neighborhood {
color: brown;
}
#NewElement {
color: green;
}
<div id="Neighborhood">
<div id="Neighbor1">Neighbor 1</div>
<div id="Neighbor2">Neighbor 2</div>
<div id="Neighbor3">Neighbor 3</div>
</div>
insertAdjacentHTML
+ outerHTML
elementBefore.insertAdjacentHTML('afterEnd', elementAfter.outerHTML)
上升空间:
insertBefore
更好(即使现有节点变量名称为3个字符长也会中断)缺点:
outerHTML
将元素转换为字符串。我们需要它,因为insertAdjacentHTML
从字符串而不是元素添加内容。快速谷歌搜索显示this script
// 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);
}
}
虽然insertBefore()
(见MDN)很棒,但大多数答案在这里引用。为了增加灵活性,并且更加明确,您可以使用:
insertAdjacentElement()
(参见MDN)这允许您引用任何元素,并将要移动的元素准确插入所需的位置:
<!-- refElem.insertAdjacentElement('beforebegin', moveMeElem); -->
<p id="refElem">
<!-- refElem.insertAdjacentElement('afterbegin', moveMeElem); -->
... content ...
<!-- refElem.insertAdjacentElement('beforeend', moveMeElem); -->
</p>
<!-- refElem.insertAdjacentElement('afterend', moveMeElem); -->
其他人考虑类似的用例:insertAdjacentHTML()
和insertAdjacentText()
参考文献:
https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElement https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentText
或者你可以简单地做:
referenceNode.parentNode.insertBefore( newNode, referenceNode )
referenceNode.parentNode.insertBefore( referenceNode, newNode )
步骤1.准备元素:
var element = document.getElementById('ElementToAppendAfter');
var newElement = document.createElement('div');
var elementParent = element.parentNode;
步骤2.追加:
elementParent.insertBefore(newElement, element.nextSibling);
insertBefore()方法与parentNode.insertBefore()
一样使用。所以要模仿这个并制作方法parentNode.insertAfter()
我们可以编写以下代码。
JavaScript的
Node.prototype.insertAfter = function(newNode, referenceNode) {
return referenceNode.parentNode.insertBefore(
newNode, referenceNode.nextSibling); // based on karim79's solution
};
// getting required handles
var refElem = document.getElementById("pTwo");
var parent = refElem.parentNode;
// creating <p>paragraph three</p>
var txt = document.createTextNode("paragraph three");
var paragraph = document.createElement("p");
paragraph.appendChild(txt);
// now we can call it the same way as insertBefore()
parent.insertAfter(paragraph, refElem);
HTML
<div id="divOne">
<p id="pOne">paragraph one</p>
<p id="pTwo">paragraph two</p>
</div>
请注意,如this article中所述,扩展DOM可能不适合您。
但是,这篇文章写于2010年,现在可能会有所不同。所以决定你自己。