I am cleaning up an old jQuery plugin of mine, and I found this code:
var foo = $some.find(theCriteria).andSelf().filter(theCriteria);
That seems dumb, like it would be equivalent to:
var foo = $some.andSelf().find(theCriteria);
I assume there's some reason I wrote the first version, but I can't think what it would be. Is the latter code functionally equivalent? Or am I missing some subtle interaction?
In the above:
$some
is a jQuery object consisting of one or more elements, which usually have child elements.theCriteria
is a compound CSS selector string, e.g. ".bar, .jim, .jam"
.andSelf()
is there because $some
may have selected a single root element that has one of the CSS classes applied, and if so I want to select it.Yes, there's a difference:
<div id="test" class="bar">
<div class="bar" />
</div>
With these expressions:
// gives both <div>
$('#test')
.find('.bar')
.andSelf()
.filter('.bar');
// only returns the inner <div>
$('#test')
.andSelf()
.find('.bar')
This is because filter()
operates on all items in the result set, whereas find()
performs a DOM search on each node inside the result set, effectively skipping them.
Besides .addBack(selector)
you could do something like this:
$('#test')
.find('.bar')
.add($('#test').filter('.bar'))
No it is not equivalent
If you want to support only jQuery 1.8+ then you can use .addBack() - Demo
var foo = $some.find(theCriteria).addBack(theCriteria);
else you can use .add
var foo = $some.find(theCriteria).add($some.filter(theCriteria));
It is not the same because of 2 reasons Demo: Fiddle
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