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");
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");
Share
Improve this question
edited Apr 24, 2019 at 16:11
DontVoteMeDown
21.5k10 gold badges71 silver badges113 bronze badges
asked Apr 24, 2019 at 16:04
user715564user715564
1,6903 gold badges26 silver badges62 bronze badges
3 Answers
Reset to default 9The 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./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:
You can use siblings("p").last()
:
jQuery(".div-class").siblings("p").last().addClass("p-class");
jQuery(".div-class").siblings("p").last().addClass("p-class");
.p-class {
color: #f00
}
<script src="https://cdnjs.cloudflare./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>
jQuery's siblings()
returns all siblings from matched selector in order they are placed. So the desired sibling will be the .last()
in the list.
Use:
jQuery(".div-class").prev("div").prev("p").addClass("p-class");
jQuery(".div-class").prev("div").prev("p").addClass("p-class");
.p-class{
font-weight: bold;
}
<script src="https://cdnjs.cloudflare./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>