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?

有帮助吗?

解决方案

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top