Thursday, April 14, 2011

How do I index an array of jQuery objects elegantly?

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?

From stackoverflow
  • If you want to execute SomejQueryFunctionForExampleShow() on some of the object why index just do:

    $("a-selector-which-returns-multiple-objects").SomejQueryFunctionForExampleShow().
    
    Will Dean : The point about my [index] is that I only want to affect a single member of the multiple objects.
  • 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.

    Will Dean : Thanks for this - eq() is what I was after. An index is the easiest way to do this, because this is being called as part of a loop which is testing a bitmask that was returned from a piece of hardware.
    Soviut : I think you'd be able to use .each(function(i) { ... }); for that
  • JQuery provides functions such as Traversing/eq and Traversing/slice for this purpose, as well as others like Traversing/filter for more complex cases.

    $("selector").eq(0).show();
    
  • You could use the filter command to filter the original wrapped set and then perform a command on the sub set (and then return to the original wrapped set with end command).

0 comments:

Post a Comment