Istiaque Ahmed
Istiaque Ahmed

Reputation: 6488

Using same argument multiple times in .before() does not work as I expected

HTML:

<div class="here">This is here</div>
<div class="insert">This is to be inserted</div>

jQuery:

$(document).ready(function() {
  var $m = $(".insert");
  $(".here").before($m);
});

It produces the expected result - cuts the insert div and pastes it before the here div. But if the code is as following,

$(".here").before($m, $m);

then insert does not appear twice before the here div. However if I use as the second argument a div other than the first one in the following way :

$(".here").before($m, $('<div class="insert2">This is insert 2</div>'));

then both insert and insert2 divs appear before the here div.

Why don't two divs appear before the here div if the two arguments are same?

Upvotes: 0

Views: 71

Answers (3)

jazZRo
jazZRo

Reputation: 1608

Thats because an element can exist just once. With $(".here").before($m, $m); You say insert element_x before '.here' and than insert element_x before '.here'. So it is moved and than moved again to the same place.

With $(".here").before($m, $('<div class="insert2">This is insert 2</div>')); you're creating a new element in the second parameter so that works fine.

To copy an element to insert it twice you can clone the element and insert both:

var $m2 = $m.clone();
$(".here").before($m, $m2);

Upvotes: 0

Salman Arshad
Salman Arshad

Reputation: 272166

What you are doing is moving an existing element from one place to another; you are not creating additional copies of it. Create copies using .clone() method and insert into desired location:

$(".here").before(
    $m         /*.attr("title", "original")*/,
    $m.clone() /*.attr("title", "copy # 1")*/,
    $m.clone() /*.attr("title", "copy # 2")*/
);

Your other example creates a new element which is why it works as expected.

Upvotes: 2

Barmar
Barmar

Reputation: 781370

When you give an existing DOM element as an argument to DOM insertion methods, it doesn't make a copy of the element, it just moves that element to the place you specify. A single DOM element can only be in one place at a time, so if you specify the same element twice, it moves it twice. If you want copies of the element, you must make them explicitly:

$(".here").before($m, $m.clone());

Upvotes: 1

Related Questions