Each and AppendTo Function in jQuery

Recently I started work on jQuery and had gone through a very interesting way of looping. As for loop, jQuery provides a core method that you can use to loop through your set of selected

DOM elements. $().each () is jQuery's for loop, which will loop through items.

I would like to try to demonstrate here how each functions works, so those who are new to jQuery can understand that the for loop works like in C#.

The structure for this is as given below:

Jquery1.jpg

Here my Ul list has multiple list elements along with a span with text ("these are even elements").

For each iteration in the code segment it checks for whether it is an odd number or even and sets the CSS class respectively. Down the line it also appended to even numberd elements into the span.

Another core method of jQuery is appendTo. For more information about appendTo please visit the following link.

The most significant fact about the appendTo() method is that it adds a selector value to the function element.

$(this).addClass("even").appendTo("#spanText");

Jquery2.jpg

Here each selected element is being appended to a given span with id "#spanText.

I will try to cover more on such types of interesting facts in the future.

The following figure shows the code segment being used in an application and how it works. The sample application has been attached for refernece.

Jquery3.jpg

Kindly let me know if you have any questions.

Up Next
    Ebook Download
    View all
    Learn
    View all