Reputation: 67193
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
?
Upvotes: 4
Views: 233
Reputation: 147363
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);
}
}
Upvotes: 5
Reputation: 85794
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.Upvotes: 5