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>
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>
$("div p").first();
or $('div p:first');
Reference: http://api.jquery.com/first/
Keep in mind that first() matches only a single element, the :first-child selector can match more than one: one for each parent.
This should work
The above code finds the first paragraph in the div as @Denver pointed and changed its
fonts-size
to10px
Here is an example that explains even more about jQuery first-of-type selector
answer was too short to post without this useless sentence.
Edit This is definitely a slow option. After looking at Jame's speed test, it looks like jQuery selectors work best when they piggy back off of css selectors.
Assuming you have a reference to the
div
already:If the first
p
will always be a direct child of thediv
, you could usechildren
instead offind
.Some alternatives include:
Note that the
eq
method will always be the fastest way to do this. Here's the results of a quick comparison of theeq
method,:eq
selector and:first
selector (I didn't bother with thefirst
method since it's just an alias ofeq(0)
):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:Should work. I think.