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];

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 :)


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


You can use the first method:

$('li').first()

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

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


You can use the first selector.

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

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

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