最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Use jQuery to find the previous sibling element - Stack Overflow

programmeradmin4浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 9

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./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>

发布评论

评论列表(0)

  1. 暂无评论