Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can these two jQuery lines produce different results?

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".
  • The 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.
like image 948
Phrogz Avatar asked Feb 13 '23 15:02

Phrogz


2 Answers

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'))
like image 120
Ja͢ck Avatar answered Feb 16 '23 05:02

Ja͢ck


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

  • andSelf() adds back the previous set of elements in your case there are not previous set of elements - this adds the document object to the element set causing undesired results
  • since you are using .find(), you are not filtering the $some object set
like image 20
Arun P Johny Avatar answered Feb 16 '23 06:02

Arun P Johny