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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With