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?
The :first selector selects the first element.
jQuery siblings() MethodThe siblings() method returns all sibling elements of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward and backwards along siblings of DOM elements.
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.
The prev() method returns the previous sibling element of the selected element. Sibling elements are elements that share the same parent.
jQuery('#myDiv').siblings('p:first')
or
jQuery('#myDiv').siblings('p').first()
would do the trick
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