Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jQuery to find the previous sibling element

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");
like image 229
user715564 Avatar asked Oct 18 '25 15:10

user715564


1 Answers

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:
like image 188
Pranav C Balan Avatar answered Oct 21 '25 05:10

Pranav C Balan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!