JQuery DOM manipulation with each ();

I am trying to do some simple DOM manipulations on multiple elements at once using jQuery using each (). I get results that I don’t understand.

Here is a jsFiddle that shows what I want to do 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 do I get the results that I have, and how can I achieve the desired results?

+7
javascript jquery dom this each
source share
3 answers

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

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

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

Here's the optimal solution:

 $('.grey').each(function () { var $this = $(this); $this.find('.red').clone().appendTo($this.find('.blue')); }); 
+4
source share

Try the following:

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); }); 
0
source share

AppendTo doesn’t work like that, personally I just use the $(this) object and grab onto what you want from there.

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

with working jsFiddle

0
source share

All Articles