Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between jQuery has() and filter() methods?

What is the difference between $.has('selecor') and $.filter('selector') methods, and which one of them is better?

Both of them seem to perform the same operation, maybe there are some performance benefits of using one instead of other?

like image 910
rajansoft1 Avatar asked Jan 16 '14 19:01

rajansoft1


1 Answers

They are quite different actually.

filter operates on the matched elements:

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

has filters based on the descendants of the matched elements:

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


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

like image 118
Fabrício Matté Avatar answered Nov 15 '22 20:11

Fabrício Matté