jquery 如果父级没有具有特定类的子级,则删除父级

tf7tbtn2  于 2023-06-22  发布在  jQuery
关注(0)|答案(5)|浏览(98)

我有一个这样的代码:

<div class='parent one'>
  <div class='yes'></div>
  <div class='yes'></div>
  <div class='yes'></div>
</div>

<div class='parent two'>
  <div></div>
  <div></div>
  <div></div>
</div>

<div class='parent three'>
  <div></div>
  <div></div>
  <div class='yes'></div>
</div>

我如何删除.parent.two,因为它没有任何与.yes的孩子?到目前为止,我已经尝试过了,它没有工作:

$('.parent div:not(.yes)').remove();
0yg35tkg

0yg35tkg1#

您可以将:not:has一起使用:

$(() => $('.parent:not(:has(.yes))').remove())
.parent{ background: orange; height: 100px; width: 100px; margin: 10px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='parent one'>
  <div class='yes'>Child of one</div>
  <div class='yes'>Child of one</div>
  <div class='yes'>Child of one</div>
</div>

<div class='parent two'>
  <div>Child of two</div>
  <div>Child of two</div>
  <div>Child of two</div>
</div>

<div class='parent three'>
  <div>Child of three</div>
  <div>Child of three</div>
  <div class='yes'>Child of three</div>
</div>
ss2ws0br

ss2ws0br2#

您可以创建一个选择器作为:not:has的组合,然后使用remove方法。因此,这将选择所有具有.parent类的元素,这些元素没有具有.yes类的子元素。

$('.parent:not(:has(.yes))')
$('.parent:not(:has(.yes))').remove()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='parent one'>
  <div class='yes'>one</div>
  <div class='yes'></div>
  <div class='yes'></div>
</div>

<div class='parent two'>
  <div>two</div>
  <div></div>
  <div></div>
</div>

<div class='parent three'>
  <div>three</div>
  <div></div>
  <div class='yes'></div>
</div>
uqxowvwt

uqxowvwt3#

这是你可以用vanilla js做的

document.querySelectorAll(".parent").forEach(ele => {
  if (ele.querySelector(".yes") == null) {
    ele.remove();
  }
})

//for checking
document.querySelectorAll(".parent").forEach(ele => {
  console.log(ele)
})
<div class='parent one'>
  <div class='yes'></div>
  <div class='yes'></div>
  <div class='yes'></div>
</div>

<div class='parent two'>
  <div></div>
  <div></div>
  <div></div>
</div>

<div class='parent three'>
  <div></div>
  <div></div>
  <div class='yes'></div>
</div>
pbwdgjma

pbwdgjma4#

你可以通过很多方式来实现这一点。基本方法是:
直接选择:
$('.parent.two').remove();
根据其索引进行选择:
$('.parent:eq(1)').remove();
基于.yes元素作为子元素的存在:
$('.parent div').not('.parent .yes').parent().remove();

4szc88ey

4szc88ey5#

检查每个父div.innerHTML,查看是否存在具有该文本的子,如果不存在,则删除父。

document.querySelectorAll("div.parent").forEach(function(parentDiv){
  if(!parentDiv.innerHTML.includes('<div class="yes">')){
    parentDiv.remove();
  }
});
<div class='parent one'>1
  <div class='yes'></div>
  <div class='yes'></div>
  <div class='yes'></div>
</div>

<div class='parent two'>2
  <div></div>
  <div></div>
  <div></div>
</div>

<div class='parent three'>3
  <div></div>
  <div></div>
  <div class='yes'></div>
</div>

相关问题