Toran Billups
Toran Billups

Reputation: 27399

jQuery append child nodes in for each

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

Upvotes: 5

Views: 19396

Answers (2)

Adam Bellaire
Adam Bellaire

Reputation: 110489

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

Upvotes: 8

RaYell
RaYell

Reputation: 70414

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.

Upvotes: 0

Related Questions