Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I index an array of jQuery objects elegantly?

Tags:

jquery

I find myself starting to write this:

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

Because I have one query which returns multiple objects, then the [index] operator returns the DOM object, not a jQuery object, so I convert it back to a jQuery object with the outer $().

This is working fine, but seems inelegant, and I feel I'm missing something about indexing into sets of jQuery objects - what's the proper way to do this?

like image 229
Will Dean Avatar asked Dec 17 '22 08:12

Will Dean


1 Answers

You don't have to index your elements at all in the case you describe. Because of the way JQuery chains its commands, any command you will be run on all the elements the previous selector returns.

The following example will hide all <a> elements:

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

If it needs to be a specific element, you should be giving it a unique ID to select:

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

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

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

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

like image 108
Soviut Avatar answered Dec 30 '22 00:12

Soviut