09-07-2008

jQuery jQuery .each loop example

Execute the function, and what is in between the curly-brackets, for each of the DOM elements that matches the selector. The keyword 'this' refers to the current element the loop is dealing with.

The function specified receives an iterator as argument by default, represented in this example here as 'i'.

$("div img").each(function(i){
   this.id = this.id + "_" + i;
});

To break out of a jQuery each loop you use 'return false' like you would use the 'break' command in a usual javascript loop:

$("div img").each(function(i){
	if (this.id == 'whatever') {
		return false; 
	}
});

Comments:

11 comments.
Your comment:

»
frederick 10/12/2010, 12:29 am
really nice tutorial :-?
Baljeetsingh 10/02/2011, 5:19 am
Thanks :)
RAGHU 18/02/2011, 8:33 am
yes it's correct
Roshan 04/05/2011, 8:05 am
good tips
Geo 12/05/2011, 7:41 am
It works ,Thanks for Sharing
4hyrt 23/06/2011, 6:21 pm
dsafdfccx
ghkg 21/12/2011, 11:17 am
kdkfgkdf gkdf gkdfg kfd kdk <script>alert("jjjjjjjjjjjjj")</script>
Raghs 10/06/2011, 2:22 pm
Thanks Buddy
sdgsdfg 23/06/2011, 6:20 pm
aaxvcxxvxc
Shiv 18/07/2011, 7:17 am
Nice
RAT 11/10/2011, 8:53 am
Nice example.

 

[x]