What is the difference between jquery has () and filter () methods

What is the difference between $ .has ('selecor') and $ .filter ('selector'), and which one is better. since both of them perform the same operation.

+8
jquery
source share
1 answer

In fact, they are completely different.

filter works with the relevant elements:

Reduce the set of matched elements to those that match the selector or pass a function test.

has based on the descendants of matching elements:

Reduce the set of matched elements to those who have a child that matches the selector or DOM element.


A practical example:

 <span class="outer">outer span</span> <div class="outer"> outer div<br> <span>descendant span</span> </div> 

 $('.outer').filter('span'); //returns the outer span $('.outer').has('span'); //returns the outer div 

Fiddle

+12
source share

All Articles