How to tell if an element is visible with jQuery

Posted in Javascript -

jQuery makes it easy to determine if an element is visible or hidden with the is() function. This post shows some examples of how to do this and also how to loop through each of the visible or hidden elements.

Check if an element is visible

In the following HTML the div is initially hidden. It might have also been hidden using jQuery after the page has loaded, or via a toggling function or so on.

<div id="foo" style="display:none"></div>

To check if it is visible use the is() function passing ":visible" as the parameter:

if( $('#foo').is(':visible') ) {
    // it's visible, do something
}
else {
    // it's not visible so do something else
}

Check if an element is hidden

This is the same as checking if an element is visible but uses :hidden instead and the logic is the reverse:

if( $('#foo').is(':hidden') ) {
    // it's hidden, do something
}
else {
    // it's not hidden so do something else
}

Note: if the element doesn't take up any space in the document, then is(':hidden') will return true even if it is effectively visible. It may be safer to instead do this:

if( !$('#foo').is(':visible') ) {
    // it's hidden, do something
}
else {
    // it's not hidden so do something else
}

Looping though visible elements

The next example uses the following HTML:

<div id="foo">
    <div>abc</div>
    <div style="display:none">def</div>
    <div>ghi</div>
</div>

To loop through the visible divs under #foo do something do this:

$("#foo div:visible").each( function() {
    document.write($(this).html()+'<br />');
});

The above example would write the following out to the document:

abc
ghi

And as with the earlier examples use :hidden instead of :visible to reverse the logic to find the hidden elements, again taking note that if the element doesn't take up any space in the document then it is considered to be :hidden.



Related posts:


Comments