Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery first of type selector?

How would I select the first <p> element in the following <div> with jQuery?

<div>     <h1>heading</h1>     <p>How do I select this element with jQuery?</p>     <p>Another paragraph</p> </div> 
like image 381
Web_Designer Avatar asked Dec 16 '11 07:12

Web_Designer


People also ask

How do you select the first element with the selector statement?

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

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.

Which selector selects the element that is the first child of its parent that is of its type?

The :first-of-type selector selects all elements that are the first child, of a particular type, of their parent.


1 Answers

Assuming you have a reference to the div already:

$(yourDiv).find("p").eq(0); 

If the first p will always be a direct child of the div, you could use children instead of find.

Some alternatives include:

$(yourDiv).find("p:eq(0)"); //Slower than the `.eq` method $(yourDiv).find("p:first");  $(yourDiv).find("p").first() //Just an alias for `.eq(0)` 

Note that the eq method will always be the fastest way to do this. Here's the results of a quick comparison of the eq method, :eq selector and :first selector (I didn't bother with the first method since it's just an alias of eq(0)):

enter image description here

like image 68
James Allardice Avatar answered Oct 06 '22 03:10

James Allardice