0

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"]')

Scoots
  • 2,767
  • 2
  • 18
  • 32

1 Answers1

4

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")
T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
  • 1
    I had to read this twice (it makes sense, just had to read it twice as it looked like it was the wrong way/using the wrong code snippet), so put another way: `$('element').is(':hidden')` *also* applies `:hidden` to multiple elements, not just to a single element - in the general case. In the linked question it just *happens* to be only one element, coincidentally. – freedomn-m Sep 11 '17 at 16:51