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>
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).
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.
The :first-of-type selector selects all elements that are the first child, of a particular type, of their parent.
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)
):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With