Jay Sun
Jay Sun

Reputation: 1601

Checking inherited visibility of DOM element with jQuery

If I have the HTML below:

<div style="display:none;">
    <span id="hello">Hey</span>
</div>

And I do alert($("#hello").css("display"));, it will say "inline". The span is clearly not visible, but since it doesn't directly have a display:none; property on it, it still says it's viewable.

How do I test whether a certain DOM element is actually visible or not, even if its parent or a parent of its parent is not displaying?

Upvotes: 3

Views: 638

Answers (4)

Wex
Wex

Reputation: 15695

Use $(selector).is(':visible')

Upvotes: 1

Nicol&#225;s Torres
Nicol&#225;s Torres

Reputation: 1345

You can use:

if ($('#myitem').is(':visible')){

/*Do some sort of stuff in here */

}

Items still animating (like using .hide or .fadeOut) will be "visible" until the animation is complete

Upvotes: 4

jbabey
jbabey

Reputation: 46647

use the .is() function along with the :hidden or :visible psuedoselectors:

http://jsfiddle.net/jbabey/ucSVx/

$('#hello').is(':hidden')

Upvotes: 0

James Allardice
James Allardice

Reputation: 165971

You can use the :visible selector, and the is method:

if($("#hello").is(":visible")) {
    //It's visible!
}

The is method returns a boolean value indicating whether or not any of the matched elements match that selector.

Upvotes: 2

Related Questions