Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Select all elements that are not descendant of a certain class

<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)');
like image 989
Ayhan Erli Avatar asked Dec 15 '11 17:12

Ayhan Erli


2 Answers

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 -->
like image 135
Felix Kling Avatar answered Oct 14 '22 15:10

Felix Kling


using wildcards either

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

or

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

may work.

like image 42
Jason Meckley Avatar answered Oct 14 '22 15:10

Jason Meckley