Search if an item is visible (JavaScript)

I have a javascript function that tries to determine if a div is visible and performs various processes with this variable. I can successfully change the visibility of elements by changing its display between none and block; but I can not save this value ...

I tried to get the value of the display attribute of the elements and find out if the element identifier is visible, but none of them worked. When I try .getAttribute, it always returns null; I am not sure why, because I know that the identifier is defined and has a display attribute.

Here is the code of two different methods I tried:

var myvar = $("#mydivID").is(":visible"); var myvar = document.getElementById("mydivID").getAttribute("display"); 

Any guidance or assistance is appreciated.

+7
source share
4 answers

The display is not an attribute; it is a CSS property inside the style attribute.

You may be looking for

 var myvar = document.getElementById("mydivID").style.display; 

or

 var myvar = $("#mydivID").css('display'); 
+9
source

Try it like this:

 $(function () { // Handler for .ready() called. if ($("#mydivID").is(":visible")) { alert('Element is visible'); } }); 

Fiddle

Remember to include the jQuery file in the head tag, as shown below.

 <head> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> </head> 
+16
source

Take a second to see what .is(":visible") does in jQuery, will we?

Here's the link: https://github.com/jquery/jquery/blob/master/src/css.js#L529

return !jQuery.expr.filters.hidden( elem );

Where

 jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0; }; 

So, it just checks the width and height of the element offset.

However, it is worth noting that when jQuery checks to see if the element is hidden (for example, when the "switch" event is triggered), it checks the display property and its existence in dom . https://github.com/jquery/jquery/blob/master/src/css.js#L43

+6
source

If you want to do this with javascript only, you can try

 window.getComputedStyle(document.getElementById("mydivID"),null).getPropertyValue('display') 
+3
source

All Articles