简体   繁体   中英

jQuery filter efficiency

I recently came across this question: How do I check if an element is hidden in jQuery?

The currently accepted answer seems to indicate that $('element').is(':hidden') is preferable to $('element:hidden') because the :hidden filter is only being applied to a single element.

But... Calling .is() also adds extra overhead as you are calling an another function.

This got me thinking, does the above reasoning for using .is() hold true if the selector is a set of elements?

And what about more extreme cases? Take the following test case:

$('element.class1:not(.class2):visible[rel="foo"]')

Is it best to leave those in the selector? Or move them all into a single filter call:

$('element').filter('.class1:not(.class2):visible[rel="foo"]')

Or is it better to chain them?

$('element').is('.class1').not('.class2').is(':visible').filter('[rel="foo"]')

The currently accepted answer seems to indicate that $('element').is(':hidden') is preferable to $('element:hidden') because the :hidden filter is only being applied to a single element.

I don't read it that way at all, and assuming you're dealing with a string , then $("some-selector:hidden") isn't applied only to a single element; it's applied to all elements matching some-selector .

Or is it better to chain them?

 $('element').is('.class1').not('.class2').is(':visible').filter('[rel="foo"]') 

That will fail, since is returns a boolean:

.is(selector)

Description: Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.

If you want to select elements matching multiple criteria, it's fine to put those criteria in the selector string. The only real question you should ask yourself is whether to use :hidden and other jQuery-isms in the string, since it means that jQuery can't pass the selection off to the browser's built-in (read: fast ) selector engine, and has to do the work itself.

For that reason, with that example, you might prefer to move the jQuery-isms out of it:

$('element.class1:not(.class2)[rel="foo"]').filter(":visible")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM