jQuery: Select all elements that are not descendan

2019-04-18 13:57发布

问题:

<div class="container" id = "0" >
   <div class="x" id = "1"> 
      <div id = "2"> 
        <p id = "3">
          <span id = "4" >text</span> 
        </p>
      <div>
    </div>

    <div id="5">
      <div id="6"> 
        <p id="7">
          <span class="x" id="8" >text</span> 
          <span id="9">text</span> 
        </p>
      <div>
    </div>
<div>

Can you help me to select all the elements :

  • that are descendant of '.container"'
  • not descendant of '.x'
  • doesn't have the class '.x' itself.

Looking at the HTML above; it should select the elements 5,6,7 and 9

  • Element 1 has class "X"
  • Elements 2 is direct child of an element-with-class"X"(Element 1)
  • Elements 3 and 4 are descendants an element-with-class"X"(Element 1)

Element 8 has class "X"


I have this selector but it keeps selecting the descendants (deep children) of element with class "X"

var elements = $('.container').find().parents(':not(.X)').andSelf().filter(':not(.X)');

回答1:

This should do it:

$('.container').find(':not(.x):not(.x *)');

Edit: Reverted to first revision again. I thought it did not work this way, but you have an error in your HTML which makes #1 parent of all elements, so none is selected.

<div class="container" id = "0" >
    <div class="x" id = "1"> 
      <div id = "2"> 
        <p id = "3">
          <span id = "4" >text</span> 
        </p>
      <div> <!-- <-- must be a closing div tag -->
    </div>

    <div id="5">
      <div id="6"> 
        <p id="7">
          <span class="x" id="8" >text</span> 
          <span id="9">text</span> 
        </p>
      <div> <!-- <-- must be a closing div tag -->
    </div>
<div> <!-- <-- must be a closing div tag -->


回答2:

using wildcards either

$(".container :not(* .x)")

or

$(":not(* .x)", ".container")

may work.