In the HTML below, I would like to add a class to the first sibling P element that is before the div with the class "div-class".
<p>hello</p>
<p>hello</p> -> add class to this element
<div><p>test</p></div>
<div class="div-class"></div>
This doesn't work:
jQuery(".div-class").prev("p").addClass("p-class");
The prev()
method only selects sibling element which is immediately before the element since you are using p
selector it won't select anything because there isn't any p
tag which is immediately before the element.
You can use prevAll()
method to get all sibling elements which is before the element and first()
method to get the nearest one among the collection.
jQuery(".div-class").prevAll("p").first().addClass("p-class");
.p-class {
color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>hello</p>
<p>hello</p>
<div>
<p>test</p>
</div>
<div class="div-class"></div>
This doesn't work:
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