jQuery each() method for iterating over collections
The each() is used to specify a function that runs for each of the matching elements.
$(selector).each(function(index,element){
// code here
});
Iterating over a list using jQuery each()
<!DOCTYPE html> <html> <head> <title>each()</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script> $(document).ready(function(){ $("li").each(function(index){ $(this).css( "backgroundColor", $(this).text() ); }); }); </script> </head> <body> <ul> <li>red</li> <li>green</li> <li>blue</li> </ul> </body> </html>
We can also stop the iteration, by returning a boolean false from the callback function.
<!DOCTYPE html> <html> <head> <title>each()</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script> $(document).ready(function(){ $("li").each(function(index){ $(this).css( "backgroundColor", $(this).text() ); if($(this).text()==="green"){ return false; } }); }); </script> </head> <body> <ul> <li>red</li> <li>green</li> <li>blue</li> </ul> </body> </html>
© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post