How to check div is display:none or block in javascript
If you’re looking to find out if a div is set to display:none or block in JavaScript, then this post is for you.
Checking the visibility of an element with JavaScript can be tricky but it doesn't have to be. With just a few lines of code, you'll be able to easily determine whether your div has been set as display:none or block.
To check div is display:none or block in javascript, we may use the JavaScript display property or getComputedStyle() method.
Check if div is display:none or not using getComputedStyle() method. #
We can use the getComputedStyle() method of the window object to check if an element is display:none or block.
Example : check if element is display:none using getComputedStyle() method. #
<script>
function myFunc(){
console.log(window.getComputedStyle(element).display)
}
</script>
Try it Yourself »
Now, we will add a condition, if the div element is display:none, we will alert "This element is hidden" otherwise "This element is not hidden".
Alert a message if an element is display:none. #
function myFunc(){
if(window.getComputedStyle(element).display == "none"){
alert("This element is hidden.")
}else{
alert("This element is not hidden.")
}
}
Try it Yourself »
Check if div element is display:none using display property. #
We can also use the style.display property of JavaScript to check if an element is display:none of block. The example is given below.
Check if div is display:none using display property. #
function myFunc(){
console.log(document.querySelector('#my-div').style.display)
}
Try it Yourself »
To do this, we’ll use document.querySelector(). This method allows us pass in any valid CSS selector and get back a reference of that element from our HTML document which we can then interact with programmatically through our script code. For example:
let myDiv = document.querySelector( '#my-div' );
Once we have access to our desired div object, all that’s left now is determining what value its style attribute holds for "display" property.
We can easily achieve this by accessing .style object associated directly onto any DOM node like so :
console.log(myDiv.style["display"]);