Weblurk
Weblurk

Reputation: 6812

How do I select the first sibling of a certain element type with jQuery?

The HTML is structured like this:

<div id="myDiv"></div>
<img src="" />
<p></p> // I want to select this element 
<h1></h1>
<p></p>
<h2></h2>

Based on my start element <div id="myDiv"> There are several more <p> siblings but I only want the first one, as seen in the code.

How can I achieve this?

Upvotes: 9

Views: 27407

Answers (3)

Sj.
Sj.

Reputation: 1422

As Olivier suggests .first() or p:first would suit your needs, though a more general solution would be to us .eq(n) - where n is the number you want starting from 0.

For instance, to select the first sibling paragraph of #myDiv you would use:

    jQuery('#myDiv').siblings('p').eq(0);

To target the third paragraph, all you would do is change the number. Remember that as it starts from 0 you effectively need to take one away from the desired target:

    jQuery('#myDiv').siblings('p').eq(2);

Upvotes: -1

Engineer
Engineer

Reputation: 48793

Try this:

jQuery('#myDiv ~ p').first()

or pure css selector(not checked the performance, but it could be the fastest solution,as it uses .querySelectorAll):

jQuery('#myDiv ~ p:first-of-type')

Upvotes: 3

OlivierH
OlivierH

Reputation: 3890

jQuery('#myDiv').siblings('p:first')

or

jQuery('#myDiv').siblings('p').first()

would do the trick

Upvotes: 30

Related Questions