How to get the first element and not use [0] in jQuery?

I am new to jQuery, sorry if this is a stupid question.

When I use it, find the element using id, I know that theres always one match, and I would use the index [0] to access it. Is there a better way to do this? For example,

var gridHeader = $("#grid_GridHeader")[0]; 
+64
javascript jquery
Jun 23 '10 at 17:02
source share
7 answers

You can use .get(0) , but ... you do not need to do this with an element found by identifier, which should always be unique. I hope this is just an oversight in the example ... if this is the case on your real page, you need to fix it so that your identifiers are unique and use a class (or other attribute) instead.

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

+67
Jun 23 '10 at 17:04 on
source share
— -

$("#grid_GridHeader:first") works.

+17
Jun 23 '10 at 17:05
source share

You can use the first method:

 $('li').first() 

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

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

+8
Jun 23 '10 at 17:27
source share

With the assumption that there is only one element:

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

... are equivalent by returning a single base element.

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

  // Return just the object ( num < 0 ? this.slice(num)[ 0 ] : this[ num ] ); 
+4
Jun 23 '10 at 17:07
source share

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

 $("#grid_GridHeader").eq(0) 
+2
Jun 23 '10 at 17:05
source share

You can use the first selector.

 var header = $('.header:first') 
+1
Jun 23 '10 at 17:06
source share

You can try the following:
yourArray.shift()

-2
Feb 21 '17 at 9:44
source share



All Articles