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?
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'));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With