Looking for jQuery find(..) method that includes the current node
Solution 1:
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')
Solution 2:
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.
Solution 3:
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.
Solution 4:
$('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')
Solution 5:
The accepted answer is very inefficient and filters the set of elements that are already matched.
//find descendants that match the selector
var $selection = $context.find(selector);
//filter the parent/context based on the selector and add it
$selection = $selection.add($context.filter(selector);