如果项具有活动类,则将类添加到父级和祖级

时间:2017-07-05 05:46:25

标签: javascript jquery html5 css3

如果我的代码看起来像下面那样,并且喜欢将show类添加到父级和祖级中。

// The last `nav-item` have `active` classs
<div class="nested-group nested-item show">
  <div class="nested-item show">
    <div class="nested-item show">
      <div class="nested-item show">
        <a class="nav-item active" href="#">Lorem</a>
        <a class="nav-item" href="#">Ipsum</a>
      </div>
    </div>
  </div>
</div>

// The last `nav-item` doesn't have `active` class
<div class="nested-group nested-item">
  <div class="nested-item">
    <div class="nested-item">
      <div class="nested-item">
        <a class="nav-item" href="#">Lorem</a>
        <a class="nav-item" href="#">Ipsum</a>
      </div>
    </div>
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

您可以使用.parents()方法定位nested-item类的所有父/祖先。

&#13;
&#13;
$('.active.nav-item').parents('.nested-item').addClass('show');
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nested-group nested-item ">
  <div class="nested-item ">
    <div class="nested-item ">
      <div class="nested-item ">
        <a class="nav-item active" href="#">Lorem</a>
        <a class="nav-item" href="#">Ipsum</a>
      </div>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;