jquery 如何将类添加到父元素?

dtcbnfnu  于 2023-05-28  发布在  jQuery
关注(0)|答案(1)|浏览(172)

对于类为“arrows”的span元素,我尝试从其父类中添加一个类为“collapse”的div,并添加一个属性为“navbar-toggler”的div。
我尝试了以下代码:

$(function() {
  $('.arrows[aria-expanded="true"]').closest('.navbar-toggler').setAttribute("aria-expanded", true);
});

$(function() {
  $('.arrows[aria-expanded="true"]').parents('.collapse').addClass('in')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="navbar-toggler collapse-icons" data-toggle="collapse" data-target="#exCollapsingNavbar10">
  <i class="material-icons add"></i>
  <i class="material-icons remove"></i>
</div>

<div class="collapse" id="exCollapsingNavbar10">
  <ul class="category-sub-menu">
    <li data-depth="1" data-id="11">
      <a class="category-sub-link" href=" ">Educație Arduino</a>
      <span class="arrows" data-toggle="collapse" data-target="#exCollapsingNavbar11" aria-expanded="true">
9nvpjoqh

9nvpjoqh1#

$('.arrows[aria-expanded=true]')
  .parents('.collapse')
  .addClass('in')
  .prev()
  .attr('aria-expanded', true);
.in {
  background: yellow;
}

.navbar-toggler[aria-expanded=true] {
  background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="navbar-toggler collapse-icons" data-toggle="collapse" data-target="#exCollapsingNavbar10">
  <i class="material-icons add"></i>
  <i class="material-icons remove"></i>
</div>

<div class="collapse" id="exCollapsingNavbar10">
  <ul class="category-sub-menu">
    <li data-depth="1" data-id="11">
      <a class="category-sub-link" href=" ">Educație Arduino</a>
      <span class="arrows" data-toggle="collapse" data-target="#exCollapsingNavbar11" aria-expanded="true"></span
    </li>
  </ul>
</div>

相关问题