Looking for jQuery find(..) method that includes the current node

Define

$.fn.findSelf = function(selector) {
    var result = this.find(selector);
    this.each(function() {
        if ($(this).is(selector)) {
            result.add($(this));
        }
    });
    return result;
};

then use

$.findSelf(selector);

instead of

$find(selector);

Sadly jQuery does not have this built-in. Really strange for so many years of development. My AJAX handlers weren't applied to some top elements due to how .find() works.


You can't do this directly, the closest I can think of is using .andSelf() and calling .filter(), like this:

$(selector).find(oSelector).andSelf().filter(oSelector)
//or...
$(selector).find('*').andSelf().filter(oSelector);

Unfortunately .andSelf() doesn't take a selector, which would be handy.


$('selector').find('otherSelector').add($('selector').filter('otherSelector'))

You can store $('selector') in a variable for speedup. You can even write a custom function for this if you need it a lot:

$.fn.andFind = function(expr) {
  return this.find(expr).add(this.filter(expr));
};

$('selector').andFind('otherSelector')

For jQuery 1.8 and up, you can use .addBack(). It takes a selector so you don't need to filter the result:

object.find('selector').addBack('selector')

Prior to jQuery 1.8 you were stuck with .andSelf(), (now deprecated and removed) which then needed filtering:

object.find('selector').andSelf().filter('selector')

Tags:

Jquery