Reputation: 6812
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
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
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
Reputation: 3890
jQuery('#myDiv').siblings('p:first')
or
jQuery('#myDiv').siblings('p').first()
would do the trick
Upvotes: 30