check if element is hidden in javascript

How to Check if Element is Hidden in JavaScript

Many HTML pages have hidden elements in order to perform processing that is not obvious. Often you may need to check if element is hidden in JavaScript. In this article, we will learn how to check if element is hidden in JavaScript.


How to Check if Element is Hidden in JavaScript

Generally, elements are hidden using “display:none” or “visibility:hidden” CSS properties. By checking these values, you can easily determine if a page is hidden or visible. If the element is hidden using display:none property, it will not take up any space. If it is hidden using visibility:hidden property, it will not take up any space.

Here is a simple function to check if a given element identified by ID myDIV, is hidden.

function myFunction() {
  var x = document.getElementById("myDIV");
  if (window.getComputedStyle(x).display === "none") {
    // Do something..

      alert('element is hidden');
  }
}

In the above function, we first select an element using its ID myDIV. Then we get the value of its display CSS property, using window.getComputedStyle() function. We check if it is equal to ‘none’. If it is so, then we display the message the element is hidden. You can always do something else with it.

If you are using visibility:hidden function, you can check if the element is hidden using, the following code.

function myFunction(element_id) {
  var x = document.getElementById(element_id);
  if (window.getComputedStyle(x).visibility === "hidden") {
    // Do something..
     alert('element is hidden');
  }
}

In the above code, we check the value of visibility CSS property, and display a message if its value is ‘hidden’.

In this article, we have learnt how to check if element is hidden in HTML page using JavaScript.

Also read:

How to Stay on Same Tab after Page Refresh
How to Select Element By Text in JavaScript
How to Select Element By Name in JavaScript
How to Get Value of Selected Radio Button
How to Disable Browser AutoFill Using JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *