Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery finding children recursively, but ignore certain elements

Lets assume the following HTML

<div id=main>
   <div id=a></div>
   <div id=b></div>
   <div id=c></div>
   <div id=d>
      <div id=d1 class="no">
        <div id=d11></div>
        <div id=d12></div>
      </div>
   </div>
   <div id=e>
      <div id=e1 class="no">
        <div id=e11></div>
        <div id=e12></div>
        <div id=e13></div>
      </div>
   </div>
 </div>

I want to select all div tags that are children of main, but want to ignore children of divs that have a class as "no".

I have currently written a recursive function to do the job. But was wondering if there is a jQuery selector to get what I want.

I want the DIVs with ids a,b,c,d,d1,e,e1

Thanks

EDIT: Created a test page here - http://jsfiddle.net/mRENV/

like image 760
Arun Avatar asked Jun 16 '11 07:06

Arun


3 Answers

It should be:

$('#main div').not('.no div')

Btw. the term children only refers to the direct descendants of an element. You want to get all descendants (not only children) of #main.

Reference: .not()

Edit: Updated your demo so that it works properly: http://jsfiddle.net/fkling/mRENV/1/

like image 180
Felix Kling Avatar answered Oct 03 '22 01:10

Felix Kling


In a single selector with no further traversal you could do this: $('#main div:not(div.no > div)');

like image 33
Useless Code Avatar answered Oct 03 '22 00:10

Useless Code


Several syntactical ways to achieve that using jQuery, my suggestion is:

var $result = $('#main').find('div:not(.no > div)');

Invoking .find()help along with the pseudo :not()help selector. This line is equivalent to:

var $result = $('#main').find('div').not('.no > div');

while the latter might be slightly faster.

like image 40
jAndy Avatar answered Oct 03 '22 01:10

jAndy