Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - Collection Iteration

Tags:

jquery

I am new to JQuery. I have a select html element. I am trying to understand how to iterate through the options in the select element. I know how to do it with traditional javascript as shown here:

for (i=0; i<mySelect.options.length; i++)
  alert(mySelect.options[i].value);

However, I'm trying to learn about JQuery more. Can someone show me the best way to iterate through a collection using JQuery?

Thank you

like image 739
user70192 Avatar asked Mar 06 '26 19:03

user70192


2 Answers

Depends on what you want to do.

  • If you just want to iterative over the collection you could use each.

  • If you want to iterate over the collection and apply a transform to each element (and get a new collection back) there is map.

  • If you just want to select a subset of your collection there is grep.

like image 63
Roman Avatar answered Mar 08 '26 09:03

Roman


First off: IMHO it's great that you learn the non-jQuery way. Watch out that you don't slip into the thinking that everything better using jQuery.

To the problem: If you have a DOM reference mySelect to the select then you can get a jQuery object of the options with $(mySelect).find("option"). The usual way to loop through them would be with jQuery's each method and an (anonymous) function:

$(mySelect).find("option").each(function() {
   alert(this.value);
})
like image 33
RoToRa Avatar answered Mar 08 '26 08:03

RoToRa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!