What do [] brackets after a Jquery selector mean?

html5-audio, javascript, jquery

Solution

jQuery is an array-like object that contains all of your matched elements. Often times, jQuery will by default apply its changes to the first element in the collection:

$("li").css("display"); // display val of first element, not all elements.

Even though many `li` elements could have been found, the jQuery object tells us about the first implicitly. We could explicitly instruct it to do so by using the `$.get` method:

$("li").get(0); // Returns first DOM element
$("li")[0]; // Also returns first DOM element

We could check the `nodeName` to verify this:

$("li").get(0).nodeName; // LI
$("li")[0].nodeName; // LI

If we look under the covers, we can see how `$.get()` is implemented:

get: function(num) {
  return num == null 
    ? this.toArray() 
    : ( num < 0 
          ? this[ this.length + num ] 
          : this[ num ] );
}

From this we can see that when no argument is provided, the entire collection of element is converted to an array, and then returned. When an argument is provided, for instance `2`, we return the element as index 2. If `-2` is provided, this is added to the length (suppose the length is 5, 5+(-2) is 3) and the resulting number is used as the index.

So with regards to your particular example:

var shuffle = $("#shuffle")[0];
shuffle.play();

jQuery is used to get any element that has the id value of `shuffle`. This returns the jQuery array-like object. But your `play()` method doesn't exist on the jQuery object, it exists on the `#shuffle` object. As such, you need to get the first element in the collection.

You could use `$.get(0)`, however as we just saw, this would just be adding one more step. Internally, jQuery would perform the same code you're performing above, `[0]`.

Problem

I'm using this code to play a preloaded mp3 file. ``` var shuffle = $("#shuffle")[0]; shuffle.play(); ``` Shuffle is my id. I got the code off the net but I CANNOT figure out what the [0] after the jquery selector does. The sound does not play if I remove it.What does it do? thanks

Original source

Related problems