Checking if an element is hidden with jQuery – the correct method

Over the last couple of days I’ve been reviewing code submitted by other programmers for an external project. Two of these developers, who shall remain nameless, were checking whether elements in a form were visible or not. This is quite a common scenario, jQuery is often used to hide, add and remove elements dynamically these days.

They were using the following method, which to give them credit, did work for 99% of their cases:

[js]if( $("form#formID input#inputID").css(‘display’) != ‘none’ ) {[/js]

As mentioned above, this method works most of the time when detecting whether an element has been hidden (display CSS attribue set to none).

Problems with jQuery checking display = none

However, in their situation, they then started hiding and showing different panels within the same form. This is where problems arose.

Checking whether an element has a display value other than none doesn’t mean its visible; if a parent element is set to hidden yet our form element is set to display correctly, the form element will be still hidden thanks to its parent.

E.g.

[html]<form id=’formID’ style=’display: none’>
<input id=’inputID’ type=’text’ style=’display: inline-block’ />
</form>[/html]

Here our textbox won’t be visible, yet the above snippet of jQuery will return TRUE because the textbox isn’t itself set to be hidden.

Simple jQuery :visible selector solution

The simple solution is to modify your jQuery to be:

[js]if( $("form#formID input#inputID").is(":visible") ) {[/js]

This will select our textbox and then test correctly whether it is visible in the DOM. This check will make sure all parent elements are visible too, as well as the original CSS display attribute.

Hope this helps a few of you guys out,

2 thoughts on “Checking if an element is hidden with jQuery – the correct method

  1. Thanks for this post. It is very helpful.

    The :visible selector check if an elements are hidden or not visible in jQuery by selecting each and every elements in a DOM that is currently visible or not. It also check for hidden elements.

Leave a Reply

Your email address will not be published. Required fields are marked *