jQuery find() Method The find() method returns descendant elements of the selected element. A descendant is a child, grandchild, great-grandchild, and so on. The DOM tree: This method traverse downwards along descendants of DOM elements, all the way down to the last descendant.
$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.
find() returns an object even when there's no matching child element in the DOM.
CODE JS: $( ". plus" ). on( "click", function() { $(this).
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')
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.
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.
$('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')
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With