Alagu
Alagu

Reputation: 2854

jQuery Selector for all items in body excluding items in specific parent

Assume this is the DOM:

<body>
    <h1>Hello World</h1>
    <div class="tooltip">
       <div class="tooltip-hd">
         This is a Tooltip for header.
       </div>
       <div class="tooltip-bd">
         Some more info about header
       </div>
    </div>

    <div class="container">
       <h2>Subheading</h2>
       <div class="tooltip">
         <div class="tooltip-hd">
           This is a Tooltip for header.
         </div>
         <div class="tooltip-bd">
           Some more info about header
         </div>
       </div>

       <p>Contents inside subheading</p>
    </div>

</body>

I want to select all children inside body, excluding the children under the class "tooltip"

The $("body").find("*").not(".tooltip") would select items

Upvotes: 0

Views: 183

Answers (1)

billyonecan
billyonecan

Reputation: 20260

I'm not sure why you'd want to do this, but the following would work (though I imagine it doesn't perform very well as it's filtering everything in the body):

var items = $('body').find('*').filter(function() {
  return !$(this).is('.tooltip') && !$(this).closest('.tooltip').length;
}).get();

This will exclude all elements which have the class .tooltip, and all elements which have an ancestor with the class .tooltip, so you'd end up with the following:

h1, div.container, h2, p

Upvotes: 1

Related Questions