Search code examples
javascriptjqueryjquery-selectorsdom-traversal

Selecting all divs except one


<div id="main">
 <div class="a"></div>
 <div class="b"><p>not me</p></div>
 <div class="b"></div>
 <div class="b"></div>
 <div class="c"></div>
</div> 

How we can write a selector to select all divs with class b except whose child is <p>not me</p> ?


Solution

  • $('div.b:not(:has(p))').........
    

    Or the readable version

    $('div.b').filter(function(){
        return !$(this).find('p').length;
    });
    

    If you want to match the content as well:

    $('div.b').filter(function(){
        return $(this).find('p').text() !== "not me";
    });
    

    Live DEMO