使用JQuery过滤以省略父项的子项

时间:2018-04-23 16:08:29

标签: javascript jquery

我想从类'popup'的所有元素中删除类'active',其中元素不在特定元素的父树中。我认为它会是这样的: -

$(".active.popup").not($("#element").parents()).removeClass("active");

但我觉得这里parents()的使用无效?

示例Html: -

<div>
    <div class="popup active">
        <!-- leave this active class - it is in parent tree of #element -->
        <div>
            <div class="popup active">
                <!-- leave this active class - it is in parent tree of #element -->
                <a id="#element"></a>
            </div>
        </div>
    </div>

    <div class="popup active">
        <!-- remove this active class - not in parent tree of #element -->
        <div>
            <div class="popup active">
                <!-- remove this active class - not in parent tree of #element -->
            </div>
        </div>
    </div>

</div>
<div>
    <div class="popup active">
        <!-- remove this active class - not in parent tree of #element -->
    </div>
</div>
</body>

1 个答案:

答案 0 :(得分:1)

&#13;
&#13;
$(document).ready(function() {
  window.disableOnActive = function() {
    var element = document.getElementById("element");
    $(".active.popup").each(function(i, v) {
      if ($(element.parentElement).has(v).length == 0) {
        $(v).removeClass("active");
      }
    })
  }
});
&#13;
.active {
  color: orange;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
  <div>
    <div id="element">
      <p class="active popup">
        I am active but not in parent
      </p>
    </div>
  </div>
  <p class="active popup">
    I am active outside the parent 1
  </p>
  <p class="active popup">
    I am active outside the parent 1
  </p>
</div>
<button onClick="disableOnActive()">Disable Active
</button>
&#13;
&#13;
&#13;