tags:

views:

74

answers:

6

I'm new to JQuery, appologies 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];
+1  A: 

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

Nick Craver
Except that `$("#id") /* jQuery object */ != $("#id").get(0) /* DOM Object */`
BrunoLM
@BrunoLM - If you want a DOM element, `document.getElementById('id')`, don't create a jQuery object just to throw it away...that's tremendously wasteful, from the selector engine to the object wrapper, it's just overkill for no good reason :)
Nick Craver
Nick I agree, maybe I was being rather silly just using jquery for everthing.
Rubans
A: 

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

$("#grid_GridHeader").eq(0)
Adam
+4  A: 

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

Mervyn
I think this is the best way to handle your issue here. It reads well, as opposed to .eq(0)
A: 

You can use the first selector.

var header = $('.header:first')
Matt
+1  A: 

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 ] );
Ken Redler
Thanks for those everything else works apart from get() which doesn't seem to get the first item.
Rubans
Actually I can see from Nick Crave's reply why that won't work
Rubans
A: 

You can use the first method:

$('li').first()

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

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

Bennidhamma