如何在不使用库的情况下在 JavaScript 中的另一个元素之后插入一个元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4793604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to insert an element after another element in JavaScript without using a library?
提问by Xah Lee
There's insertBefore()
in JavaScript, but how can I insert an element afteranother element without using jQuery or another library?
还有insertBefore()
在JavaScript,但我怎么能插入一个元素后,另一种元素,而不使用jQuery或其他库?
回答by karim79
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
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.
referenceNode
您要放置的节点在哪里newNode
。IfreferenceNode
是其父元素中的最后一个子元素,这很好,因为referenceNode.nextSibling
will 是null
并insertBefore
通过添加到列表的末尾来处理这种情况。
So:
所以:
function insertAfter(newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
You can test it using the following snippet:
您可以使用以下代码段对其进行测试:
function insertAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
var el = document.createElement("span");
el.innerHTML = "test";
var div = document.getElementById("foo");
insertAfter(div, el);
<div id="foo">Hello</div>
回答by Armando
Straightforward JavaScript Would Be the Following:
简单的 JavaScript 如下:
Append Before:
追加之前:
element.parentNode.insertBefore(newElement, element);
Append After:
之后追加:
element.parentNode.insertBefore(newElement, element.nextSibling);
But, Toss Some Prototypes In There For Ease of Use
但是,为了便于使用,在那里扔了一些原型
By building the following prototypes, you will be able to call these function directly from newly created elements.
通过构建以下原型,您将能够直接从新创建的元素调用这些函数。
newElement.appendBefore(element);
newElement.appendAfter(element);
newElement.appendBefore(element);
newElement.appendAfter(element);
.appendBefore(element) Prototype
.appendBefore(element) 原型
Element.prototype.appendBefore = function (element) {
element.parentNode.insertBefore(this, element);
},false;
.appendAfter(element) Prototype
.appendAfter(element) 原型
Element.prototype.appendAfter = function (element) {
element.parentNode.insertBefore(this, element.nextSibling);
},false;
And, To See It All In Action, Run the Following Code Snippet
并且,要查看所有操作,请运行以下代码片段
/* 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>
回答by James Long
A quick Google search reveals 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);
}
}
回答by bit-less
Though insertBefore()
(see MDN) is great and referenced by most answers here. For added flexibility, and to be a little more explicit, you can use:
虽然insertBefore()
(参见MDN)很棒并且被这里的大多数答案引用。为了增加灵活性,并且更明确一点,您可以使用:
insertAdjacentElement()
(see MDN) This lets you reference any element, and insert the to-be moved element exactly where you want:
insertAdjacentElement()
(请参阅MDN)这使您可以引用任何元素,并将要移动的元素准确插入到您想要的位置:
<!-- refElem.insertAdjacentElement('beforebegin', moveMeElem); -->
<p id="refElem">
<!-- refElem.insertAdjacentElement('afterbegin', moveMeElem); -->
... content ...
<!-- refElem.insertAdjacentElement('beforeend', moveMeElem); -->
</p>
<!-- refElem.insertAdjacentElement('afterend', moveMeElem); -->
Others to consider for similar use cases: insertAdjacentHTML()
and insertAdjacentText()
其他类似用例要考虑的:insertAdjacentHTML()
和insertAdjacentText()
References:
参考:
https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElementhttps://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTMLhttps://developer.mozilla.org/en-US/docs/Web/API/Element/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
回答by golopot
The method node.after
(doc) inserts a node after another node.
该方法node.after
( doc) 在另一个节点之后插入一个节点。
For two DOM nodes node1
and node2
,
对于两个 DOM 节点node1
和node2
,
node1.after(node2)
inserts node2
after node1
.
node1.after(node2)
node2
之后插入node1
。
This method is not available in older browsers, so usually a polyfill is needed.
此方法在旧浏览器中不可用,因此通常需要一个 polyfill。
回答by Mister SirCode
2018 Solution (Bad Practice, go to 2020)
2018 年解决方案(不良做法,转到 2020 年)
I know this question is Ancient, but for any future users, heres a modified prototype
this is just a micro polyfill for the .insertAfter function that doesnt exist
this prototype directly adds a new function baseElement.insertAfter(element);
to the Element prototype:
我知道这个问题很古老,但是对于任何未来的用户,这是一个修改后的原型,这只是不存在的 .insertAfter 函数的微填充,这个原型直接baseElement.insertAfter(element);
向 Element 原型添加了一个新函数:
Element.prototype.insertAfter = function(new) {
this.parentNode.insertBefore(new, this.nextSibling);
}
Once youve placed the polyfill in a library, gist, or just in your code (or anywhere else where it can be referenced)
Just write document.getElementById('foo').insertAfter(document.createElement('bar'));
将 polyfill 放入库、gist 或代码中(或其他任何可以引用的地方)后,只需编写 document.getElementById('foo').insertAfter(document.createElement('bar'));
2019 Solution (Ugly, go to 2020)
2019解决方案(丑,去2020)
New Edit: You SHOULD NOT USE PROTOTYPES. They overwrite the default codebase and arent very efficient or safe and can cause compatibility errors, but if its for non-commercial projects, it shouldnt matter.if you want a safe function for commercial use, just use a default function. its not pretty but it works:
新编辑:你不应该使用原型。它们会覆盖默认的代码库,效率不高或不安全,可能会导致兼容性错误,但如果用于非商业项目,则无关紧要。如果您想要一个用于商业用途的安全功能,只需使用默认功能。它不漂亮,但它有效:
function insertAfter(el, newEl) {
el.parentNode.insertBefore(newEl, this.nextSibling);
}
// use
const el = document.body || document.querySelector("body");
// the || means "this OR that"
el.insertBefore(document.createElement("div"), el.nextSibling);
// Insert Before
insertAfter(el, document.createElement("div"));
// Insert After
2020 Solution
2020解决方案
Current Web Standards for ChildNode: https://developer.mozilla.org/en-US/docs/Web/API/ChildNode
ChildNode 的当前 Web 标准:https: //developer.mozilla.org/en-US/docs/Web/API/ChildNode
Its currently in the Living Standards and is SAFE.
它目前在生活标准中并且是安全的。
For Unsupported Browsers, use this Polyfill: https://github.com/seznam/JAK/blob/master/lib/polyfills/childNode.js
对于不受支持的浏览器,请使用此 Polyfill:https: //github.com/seznam/JAK/blob/master/lib/polyfills/childNode.js
Someone mentioned that the Polyfill uses Protos, when I said they were bad practice. They are, especially when they are used incorrectly, like my solution for 2018.However, that polyfill is on the MDN Documentation and uses a kind of initialization and execution that is safer. Plus it IS for older browser support, in the day and age where Prototype Overwriting wasn't so bad.
有人提到 Polyfill 使用 Protos,当我说他们是不好的做法时。它们是,尤其是当它们使用不当时,就像我 2018 年的解决方案一样。但是,该 polyfill 位于 MDN 文档中,并使用了一种更安全的初始化和执行方式。此外,它是为旧浏览器支持,在原型覆盖还不错的时代。
How to use the 2020 Solution:
如何使用 2020 解决方案:
const el = document.querySelector(".class");
// Create New Element
const newEl = document.createElement("div");
newEl.id = "foo";
// Insert New Element BEFORE
el.before(newEl);
// Insert New Element AFTER
el.after(newEl);
// Remove Element
el.remove();
// Remove Child
newEl.remove(); // This one wasnt tested but should work
回答by olvlvl
Or you can simply do:
或者你可以简单地做:
referenceNode.parentNode.insertBefore( newNode, referenceNode )
referenceNode.parentNode.insertBefore( referenceNode, newNode )
回答by Malik Khalil
Step 1. Prepare Elements :
步骤 1. 准备元素:
var element = document.getElementById('ElementToAppendAfter');
var newElement = document.createElement('div');
var elementParent = element.parentNode;
Step 2. Append after :
步骤 2. 在 之后追加:
elementParent.insertBefore(newElement, element.nextSibling);
回答by Dmytro Dzyubak
insertBefore() method is used like parentNode.insertBefore()
.
So to imitate this and make a method parentNode.insertAfter()
we can write the following code.
insertBefore() 方法像parentNode.insertBefore()
. 所以为了模仿这个并制作一个方法,parentNode.insertAfter()
我们可以编写以下代码。
JavaScript
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
HTML
<div id="divOne">
<p id="pOne">paragraph one</p>
<p id="pTwo">paragraph two</p>
</div>
Note, that extending the DOM might not be the right solution for You as stated in this article.
请注意,这延长了DOM可能不适合你的解决方案中所述这篇文章。
Hovewer, this article was written in 2010 and things might be different now. So decide on Your own.
然而,这篇文章写于 2010 年,现在情况可能有所不同。所以决定你自己。
回答by Darlesson
Ideally insertAfter
should work similar to insertBefore. The code below will perform the following:
理想情况下insertAfter
应该与insertBefore类似。下面的代码将执行以下操作:
- If there are no children, the new
Node
is appended - If there is no reference
Node
, the newNode
is appended - If there is no
Node
after the referenceNode
, the newNode
is appended - If there the reference
Node
has a sibling after, then the newNode
is inserted before that sibling - Returns the new
Node
- 如果没有孩子,
Node
则追加新的 - 如果没有引用
Node
,Node
则追加新的 - 如果
Node
引用后没有Node
,Node
则追加新的 - 如果该引用之后
Node
有一个兄弟,则Node
在该兄弟之前插入新的 - 返回新的
Node
Extending Node
扩展 Node
Node.prototype.insertAfter = function(node, referenceNode) {
if (node)
this.insertBefore(node, referenceNode && referenceNode.nextSibling);
return node;
};
One common example
一个常见的例子
node.parentNode.insertAfter(newNode, node);
See the code running
查看运行的代码
// 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>