首页 > 解决方案 > 如何从选择器中排除一个 div 元素和他的所有孩子?

问题描述

我在 jquery 中编写了一个脚本,在选择器 * (all)的帮助下将类添加到页面上的所有元素。我想与他的所有孩子一起排除 div 的一个元素。我想知道该怎么做。我尝试使用伪类 :not包括提到的 div,但我也不知道如何排除他的孩子。你们中的任何人都可以帮我解决这个问题吗?

伪类代码 :not

$(document).ready(function(){
   $('#yellow-background').click(function(){
      $(':not(div[aria-label="Slajder"])').addClass("yellow-background");
});

正常代码:

$(document).ready(function(){
   $('#yellow-background').click(function(){
      $('*').addClass("yellow-background");
});

标签: htmljquerycsspseudo-class

解决方案


所有元素?为什么不做一个黄色叠加层并在中间显示 div呢?

反正

$("*:not('div[aria-label=Slajder] *')").addClass("yellow-background");

比写更难

$('*').not('div[aria-label="Slajder"] *').addClass("yellow-background");

由于报价,但两者都有效

$(function() {
  $('#yellow-background').click(function() {
    $('*').not('div[aria-label="Slajder"] *').addClass("yellow-background");
  });
});
.yellow-background {
  background-color: yellow
}
[aria-label=Slajder] { background-color: red }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="yellow-background">Yellow</button>

<div>Content
  <div>content
    <div aria-label="Slajder"><h1>Slajder </h1>
      <div>
        exluded content
          <div>more exluded content</div>
      </div>
    </div>
    more content
  </div>
</div>


推荐阅读