tags:

views:

4441

answers:

2

In the below code I'm trying to loop through each child node and append the child to another element - what is the correct syntax inside the loop?

$(this).children().each(    
    $(div).appendChild(this.childNodes.length - 1);
);
A: 

You should use a function callback or anonymous function in each call:

$(this).children().each(function() {
    $(div).appendChild(this.childNodes.length - 1);
});

or

function doSomething() {
    $(div).appendChild(this.childNodes.length - 1);
}

$(this).children().each(doSomething);

I'm not sure if your code couldn't been improved but there is little I can say when I see only the small portion of it.

RaYell
+3  A: 

Within the each() function, this refers to the thing you're iterating on, in this case the children(). It's not the this of the original jQuery object.

Therefore:

$(this).children().each(function() {    
    $(div).appendChild($(this));
});
Adam Bellaire