user1721135
user1721135

Reputation: 7092

jquery insertAfter() inserts clone too

I have a strange thing happening in my js script.

When the click function is executed, one element is supposed to be inserted below another one, but for some reason, the elements clone is inserted there as well.

How come? The cloning is happening outside the click function.

Pls help me understand what is going on.

http://jsbin.com/unenil/1/edit

$("button").click(function() {
  $(".one").insertAfter(".two");
  $(".status").text("done");
});


var clone_one = $(".one").clone();
var clone_two = $(".two").clone();
$("body").append(clone_one);
$("body").append(clone_two);

Basically I dont understand why the click function in this case has anything to do with the cloning which takes place outside of it.

Upvotes: 0

Views: 2511

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382334

The cloned element has the one class, so his clone too.

Therefore $(".one") contains both the cloned and the clone.

A solution would be to keep a reference to the original element and to insert it :

var original = $(".one");
var clone_one = original.clone();
var clone_two = $(".two").clone();
$("body").append(clone_one);
$("body").append(clone_two);

$("button").click(function() {
  original.insertAfter(".two");
  $(".status").text("done");
});

Upvotes: 1

Related Questions