When I have the HTML:
<div>
<p id="first">First paragraph!</p>
<p id="second">Second paragraph!</p>
</div>
And I run the script:
var second = $('#second');
$('#second').insertBefore(second);
The result is:
<div>
<p id="first">First paragraph!</p>
</div>
I know the code is nonsensical but I'm writing code where it's possible that the item I'm inserting is equal to the item I'm inserting before.
Can someone help me understand why I got the results above? What happened to #second
?
According to the W3C DOM 3 spec:
Note: Inserting a node before itself is implementation dependent.
When inserting a node, if it's already in the DOM it is first removed. So you are then trying to insert it before a node (itself) that is no longer in the DOM. You should test if the two nodes are the same and if they are, don't do the insert.
A plain js function to do the above is:
function doInsert(insertNode, beforeNode) {
if (insertNode != beforeNode) {
beforeNode.parentNode.insertBefore(insertNode, beforeNode);
}
}
Though the spec is unclear on what should happen, my guess is:
#second
is first removed from the DOM so that it can be inserted somewhere else.#second
, but, since #second
isn't in the DOM anymore, it has no place to go.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With