Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`insertBefore()` or `insertAfter()` deletes the element when the origin and the destination are the same

It looks like when insertBefore() or insertAfter() has the same element as the origin and the destination, the element is deleted. Is my understanding correct?

$('#foo').insertBefore($('#foo'))

Is this a feature? If so, what other gotchas are there with these functions?

like image 665
sawa Avatar asked Jan 13 '13 17:01

sawa


2 Answers

This is because insertBefore and insertAfter remove an element and move it. Once you've removed the element it no longer exists for the origin element to be inserted before (or after). To achieve the cloning effect you might be looking for, try:

$('#foo').clone().insertBefore($('#foo'))

like image 109
Cecchi Avatar answered Oct 27 '22 18:10

Cecchi


It actually seems that it is a known bug (not a feature), although there may be an incoming fix (1.9 release).

From the bug comments:

Since jQuery.domManip passes in a fragment, jQuery.clean moves #x to the fragment. Later when it gets to the callback in jQuery.after, the original parentNode is gone.

like image 24
Igor Avatar answered Oct 27 '22 18:10

Igor