Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery append child nodes in for each

Tags:

jquery

foreach

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);
);
like image 829
Toran Billups Avatar asked Sep 04 '09 13:09

Toran Billups


People also ask

How to add child in jQuery?

The .append() method inserts the specified content as the last child of each element in the jQuery collection (To insert it as the first child, use .prepend() ).

How to append input in jQuery?

jQuery append() MethodThe append() method inserts specified content at the end of the selected elements. Tip: To insert content at the beginning of the selected elements, use the prepend() method.

How to append a child in JavaScript?

Syntax of JavaScript appendChild:parentNode. appendChild(childNode); The childNode is the node that we want to append to the parent node parentNode . appendChild() will return the appended child.

How jQuery append works?

The jQuery append() method is used to insert specified content as the last child (at the end of) the selected elements in the jQuery collection. The append () and appendTo () methods are used to perform the same task. The only difference between them is in the syntax.


1 Answers

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));
});
like image 92
Adam Bellaire Avatar answered Sep 18 '22 22:09

Adam Bellaire