Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]; 
like image 254
Rubans Avatar asked Jun 23 '10 17:06

Rubans


People also ask

How do I get the first element of a list in jQuery?

The :first selector selects the first element. Note: This selector can only select one single element. Use the :first-child selector to select more than one element (one for each parent). This is mostly used together with another selector to select the first element in a group (like in the example above).

What does $() mean in jQuery?

In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery.

Is first child jQuery?

It is a jQuery Selector used to select every element that is the first child of its parent. Return Value: It selects and returns the first child element of its parent.

How do I get the first row of a table in jQuery?

You could also have table > thead > tr and then table > tbody > tr. So you might need to specify whether you want the first row from the thead or the tbody. find('tr:first') will select the tr in the thead.


2 Answers

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

like image 147
Nick Craver Avatar answered Sep 18 '22 00:09

Nick Craver


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

like image 25
Mervyn Avatar answered Sep 20 '22 00:09

Mervyn