Question

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?

Was it helpful?

Solution

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'));
});

OTHER TIPS

Try this:

http://jsfiddle.net/4T52A/6/

    // 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 () {
    var blue = $('.blue', this);
    $('.red', this).clone().appendTo(blue);    
});

The appendTo doesn't work quite that way, personally I'd just use the $(this) object and grab what you want from there.

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

with a working jsFiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top