Apply jQuery selector to a container AND its descendants

Viewed 36

With jQuery I can easily find/select all elements inside a container that match a given selector:

$('.some_class', container);

But what if I want to include the container itself, if it matches the selector?

I think the following would do the trick.

$('.some_class', container).add($(container).filter('.some_class'));

But is there an easier way? Ideally something where I don't have to repeat the selector.

Expected behavior

<div class="container common">
  <div class="child common"></div>
</div>

The following function does what I want, I am just wondering if there is a simpler solution out of the box.

function findInContainerAndDescendants(selector, $container) {
  return $(selector, context).add($(context).filter(selector));
}

var $container = $('.container');
findInContainerAndDescendants('.common', $container)  -> both container and child.
findInContainerAndDescendants('.child', $container)  -> just the child.
1 Answers
Related