Can these two jQuery lines give different results?

I am cleaning up the old jQuery plugin and found this code:

var foo = $some.find(theCriteria).andSelf().filter(theCriteria);

This seems dumb, as it would be equivalent:

var foo = $some.andSelf().find(theCriteria);

I assume that for some reason I wrote the first version, but I can’t think what it will be. Is the latest code functionally equivalent? Or am I missing some subtle interaction?

In the above example:

  • $some - A jQuery object consisting of one or more elements, which usually have children.
  • theCriteriais a complex CSS selector string, for example. ".bar, .jim, .jam".
  • andSelf()exists because it $somecan select one root element that has one of the applicable CSS classes, and if so, I want to select it.
+4
2

, :

<div id="test" class="bar">
  <div class="bar" />
</div>

:

// gives both <div>
$('#test')
   .find('.bar')
   .andSelf()
   .filter('.bar');

// only returns the inner <div>
$('#test')
   .andSelf()
   .find('.bar')

, filter() , find() DOM node , .

.addBack(selector) - :

$('#test')
   .find('.bar')
   .add($('#test').filter('.bar'))
+5

,

jQuery 1.8+, .addBack() -

var foo = $some.find(theCriteria).addBack(theCriteria);

else .add

var foo = $some.find(theCriteria).add($some.filter(theCriteria));

- 2 . Demo: Fiddle

  • andSelf() - ,
  • .find(), $
+3

Source: https://habr.com/ru/post/1529926/


All Articles