If I defined a DIV as such
<div id='myDiv' style='display:none;'>inner stuff</div>
I can check it's current display value as such
document.getElementById('myDiv').style.display;
And this returns a string == 'none'.
But, if I set my display style via a class the above statement returns a string of length zero.
<style>
.myDivStyle {display:none;}
</style>
<div id='myDiv' class='myDivStyle'>inner stuff</div>
<script>
var x = document.getElementByID('myDiv').style.display == ''; // returns true
</script>
Indeed the DIV is hidden in both cases, but in the latter case, how do I test that it is hidden (e.g. display=none) from javascript code?
CodePudding user response:
You can use getComputedStyle
to get the styles used on an element and not just on the style property.
var styles = getComputedStyle(document.getElementById('myDiv'));
var display = styles.getPropertyValue('display')
console.log(display);
.myDivStyle {display:none;}
<div id='myDiv' class='myDivStyle'>inner stuff</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Use window.getComputedStyle
to get the CSS properties of the element and CSSStyleDeclaration.getPropertyValue
to get the value of the display
property:
<style>
.myDivStyle {display:none;}
</style>
<div id='myDiv' class='myDivStyle'>inner stuff</div>
<script>
var x = window.getComputedStyle(document.getElementById('myDiv')).getPropertyValue("display")
console.log(x)
</script>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
I generally use HTMLElement.hidden
for handling the visibility of a div.
In order to get the status you can just access the property like this:
var x = document.getElementByID('myDiv').hidden
It will return a boolean value, indicating if the element is hidden or not.
CodePudding user response:
You can check by using the below code.
if(document.querySelector('.myDivStyle').offsetParent == null)
{
// means element is hidden
}
Or you can also check if that element has particular class which causes element to hide. e.g
document.querySelector('.hidden').classList.contains('myDivStyle')