You can use jQuery to check if an element is hidden due to a display: none
CSS rule. The is()
method can be used with the :hidden
selector to check if an element is not visible.
HTML
<div id="myElement" style="display:none;"></div>
JavaScript
// Check if the element is hidden
if ($("#myElement").is(":hidden")) {
console.log("The element is hidden!");
} else {
console.log("The element is visible!");
}
This can be useful for detecting if an element is hidden or visible, and performing different actions based on its visibility state.
jQuery check if display: none example
Simple example code uses the is()
method to check if an element is hidden:
<!DOCTYPE html>
<html>
<head>
<title>Check If Element Is Hidden</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="myDiv" style="display: none;">This div is hidden.</div>
<button id="checkButton">Check if hidden</button>
<script>
$(document).ready(function() {
$('#checkButton').click(function() {
if ($('#myDiv').is(':hidden')) {
console.log('The div is hidden.');
} else {
console.log('The div is visible.');
}
});
});
</script>
</body>
</html>
Output:
First, define a div with the ID “myDiv” that has a display: none
style attribute also defines a button with the ID “checkButton” that we use to trigger the check.
When the button is clicked the is()
the method is to check if the #myDiv
element is hidden using the :hidden
selector.
Do comment if you have any doubts or suggestions on this jQuery topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version