Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Result of Trying to Insert an Element Before Itself

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?

like image 220
Jonathan Wood Avatar asked Dec 27 '22 18:12

Jonathan Wood


2 Answers

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.

Edit

A plain js function to do the above is:

function doInsert(insertNode, beforeNode) {
  if (insertNode != beforeNode) {
    beforeNode.parentNode.insertBefore(insertNode, beforeNode);
  }
}
like image 70
RobG Avatar answered Dec 29 '22 10:12

RobG


Though the spec is unclear on what should happen, my guess is:

  1. #second is first removed from the DOM so that it can be inserted somewhere else.
  2. Now we try to insert it before #second, but, since #second isn't in the DOM anymore, it has no place to go.
like image 44
Matchu Avatar answered Dec 29 '22 08:12

Matchu