I came across this question when I was looking for an answer, how to logically check if an HTML element is visible or not in JavaScript. Although Pravin answers what to do correctly, I noticed that if the display value, for example,
element.style.display === 'inline'
then Pravin’s code probably won’t work for this case, because it only checks the values "none" and "block" .
In addition, I needed to understand how to correctly read the style.display property so that it would not appear as an empty line in the output of console.info () when debugging unit tests. I don’t have enough reputation to comment on the accepted answer, so here’s another suggestion. The actual value of style.display can be read using the function
window.getComputedStyle()
As a good example, I wrote the isLabelVisible function to check the visibility of a linked label for some <select> dropdowns.
Here is my solution for the isLabelVisible function, only using JavaScript:
const isLabelVisible = (id) => { const styles = window.getComputedStyle(document.querySelector('label[for=${id}]'), null); if (styles.display === 'none') return false; return true;
};
Elements must be part of the DOM tree in the body of the document. For example, flex or grid or block will be recognized as “visible” using this logic. Only none values will be shown as hidden on the page.
source share