How can I objectively index an array of jQuery objects?

I am starting to write this:

$($("a-selector-which-returns-multiple-objects")[index]).SomejQueryFunctionForExampleShow() 

Since I have one query that returns multiple objects, the [index] operator returns a DOM object, not a jQuery object, so I will convert it back to a jQuery object with external $() .

This works fine, but seems inelegant, and I feel like I'm missing something about indexing into jQuery object sets - what's the right way to do this?

+4
source share
4 answers

You do not need to index your items at all if you are describing. Due to the way jQuery combines its commands, any command you will run on all elements returned by the previous selector.

In the following example, all <a> elements will be hidden:

 $(document).ready(function() { $("a").hide(); }); 

If this should be a specific element, you must provide it with a unique identifier:

 $(document).ready(function() { $("#my-unique-id").hide(); }); 

If you want to return a specific index as a jQuery object, you must use the eq function .

 $(document).ready(function() { $("a").eq(0).hide(); }); 

But then again, in your case, you don't need an index at all.

+10
source

JQuery provides features such as Traversing / eq and Traversing / slice for this purpose, as well as others such as Traversing / filter for more complex cases.

 $("selector").eq(0).show(); 
+2
source

If you want to execute SomejQueryFunctionForExampleShow () on some object, why exactly the index:

 $("a-selector-which-returns-multiple-objects").SomejQueryFunctionForExampleShow(). 
0
source

You can use the filter command to filter the original wrapped set, and then run the command on a subset (and then return to the original wrapped set with end command ).

0
source

All Articles