从选择中移除特定父母的子女

时间:2015-10-14 09:27:36

标签: javascript jquery

以下是我的html

的结构
<div class="parent">
//many other elements
<div class="child">
<div class="grandchild"></div>

</div>
</div>

我想选择父级内的所有元素,除了子元素

中的元素

我尝试了下面没有工作的那个

$(".parent *:not(.child *)")

我该如何选择?

5 个答案:

答案 0 :(得分:2)

试试这个:

$('.parent *').filter(function(){
      return $(this).parents('.child').length === 0;
});

这将选择.parent内的所有元素,但.child

的儿童/子孩子除外

答案 1 :(得分:2)

$('.parent *:not(.child, .child *)')

试试这个。

虽然你可能想要这个:

$(".parent > *:not(.child)")

答案 2 :(得分:1)

试试这个: 将在父类 .parent 下选择以class child开头的所有div。

$('.parent div[class^="child"]')

答案 3 :(得分:1)

$('.parent *').not('.child *')

答案 4 :(得分:1)

  

我想选择父级内的所有元素,除了里面的元素   子

你可以使用find方法。 它会在课程child

中找到除孩子以外的所有后代/孩子
$(".parent").find("*").not($(".child").children()).each(function(){
alert($(this).prop("class"));
});