[javascript] How do I get first element rather than using [0] in jQuery?

I'm new to jQuery, apologies if this is a silly question.

When I use it find an element using the id, I know theres always one match and in order to access it I would use the index [0]. Is there a better way of doing this? For e.g.

var gridHeader = $("#grid_GridHeader")[0];

This question is related to javascript jquery

The answer is


You can use .get(0) as well but...you shouldn't need to do that with an element found by ID, that should always be unique. I'm hoping this is just an oversight in the example...if this is the case on your actual page, you'll need to fix it so your IDs are unique, and use a class (or another attribute) instead.

.get() (like [0]) gets the DOM element, if you want a jQuery object use .eq(0) or .first() instead :)


You can try like this:
yourArray.shift()


http://api.jquery.com/eq/

$("#grid_GridHeader").eq(0)

You can use the first selector.

var header = $('.header:first')

You can use the first method:

$('li').first()

http://api.jquery.com/first/

btw I agree with Nick Craver -- use document.getElementById()...


With the assumption that there's only one element:

 $("#grid_GridHeader")[0]
 $("#grid_GridHeader").get(0)
 $("#grid_GridHeader").get()

...are all equivalent, returning the single underlying element.

From the jQuery source code, you can see that get(0), under the covers, essentially does the same thing as the [0] approach:

 // Return just the object
 ( num < 0 ? this.slice(num)[ 0 ] : this[ num ] );

$("#grid_GridHeader:first") works as well.