Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery DOM manipulation with each();

I'm trying to do some simple DOM manipulation on several elements at once with jQuery using each(). I'm getting results that I don't understand.

Here is a jsFiddle that shows what I want to happen VS what actually happens:

http://jsfiddle.net/kthornbloom/4T52A/2/

And here is the JS:

// Step One: Append one blue box within each grey box

$('.grey').append('<div class="blue"></div>');

// Step Two: Make one copy of the red box already there, and place it within the new blue box.

$('.grey').each(function () {
    $('.red', this).clone().appendTo('.blue', this);
});

Why am I getting the results I am, and how can I acheive the desired results?

like image 770
kthornbloom Avatar asked Mar 03 '14 19:03

kthornbloom


1 Answers

That is because context selector doesnt work in the .append(). The fastest solution (not optimal) is to recreate a new jQuery object :

$('.red', this).clone().appendTo($('.blue', this));

Fiddle : http://jsfiddle.net/4T52A/3/

Here an optimal solution :

$('.grey').each(function () {
    var $this = $(this);
    $this.find('.red').clone().appendTo($this.find('.blue'));
});
like image 87
Karl-André Gagnon Avatar answered Sep 29 '22 02:09

Karl-André Gagnon