Alex Rivera | Logout

jQuery first of type selector?

Asked 2011-12-16T07:40:27.207
30

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>
Edit
Report

2 Answers

61

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

answered 2011-12-16T07:42:24.417
1

You almost know the answer (from your post title). There is a selector in jQuery called :first-of-type. Use it to find and add class to the first p tag automatically, like so:

$("div p:first-of-type").addClass('someClass');
answered 2013-05-05T05:28:06.610

Your Answer