views:

63

answers:

2

I've never had this issue before, so I'm somewhat lost. I'm getting two different results using essentially the same underlying code. The first way is this:

$(".myClassSelector").append(somejQueryObject);

The second way, which doesn't appear to work the same, is this:

$(".myClassSelector").each(function() { $(this).append(somejQueryObject) });

The second example only appends somejQueryObject to the last .myClassSelector found.

+5  A: 

My guess is that with the first approach jQuery internally clones the jQuery object for each of the matched elements of the selector, while with the second it just keeps appending the same object (thus removing it from earlier appended elements). Try this:

$(".myClassSelector").each(function() { $(this).append(somejQueryObject.clone()) });
reko_t
I think that is it. It is the same object being 'moved' with each 'add' until the last one. +1
o.k.w
That was it... but I'm very disappointed in the way that works. It should be that .append() as a whole works the same on every object, either a single, or multiple... I wonder actually if it is a bug.
hal10001
It's definitely not a bug, and in many applications you actually want to the object around instead of cloning (think draggable/droppable for one).
reko_t
A: 

When you use append on a jQuery object, it moves the object form its current location to the new location. Each iteration of your loop moves somejQueryObject to the next element. clone() is needed if you want to append a copy to each element.

Eric