How to tell if an element is visible with jQuery
Posted September 18th, 2009 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:
- Relatively moving a div left or right with jQuery (Friday, August 28th 2009)
- Find the index of the element that was clicked with jQuery (Tuesday, May 19th 2009)
- Loop through selected elements with jQuery (Revised) (Tuesday, April 14th 2009)
- How to tell if an element exists with jQuery (Friday, April 10th 2009)
- Get the total number of matched elements with jQuery (Tuesday, March 31st 2009)
- Show and hide an element with jQuery - Part 1 of 2 (Friday, February 27th 2009)

Comments
blog comments powered by Disqus