Ad

Filter Out All Elements In A JQuery Result Set That Have A Parent (at Any Level) With A Certain Class

I'm trying to apply some jQueryUI functionality to elements all throughout my SPA, however I'm having trouble omitting elements contained in a certain parent. I'm not actually sure if jQuery can do what I'm asking right now.

The bit of relevant code:

function initializeControls($container) {
    var $context;

    if ($container != undefined)
        $context = $container;
    else
        $context = $("html");

    $context = //$context, but ignoring all .no-controls elements and ALL children

    //do stuff...
}

Simply put, I want all elements in $context where no parent element, first parent or otherwise, has the .no-controls class.

It sounds simple, but I cannot seem to get this to work. I've tried different combinations of .find(), .filter(), .remove()... but it never seems to do exactly what I need.

Any tips?

Ad

Answer

Can use closest() in a filter()

var $filteredCollection = $context.filter(function(){
  return !$(this).closest('.no-controls').length;
});

closest() inspects the element itself and all ancestors

Ad
source: stackoverflow.com
Ad