[Solved -10 Answers] How to check if an element is hidden in jQuery
It is possible to toggle the visibility of an element, using the functions .hide(), .show() or .toggle()
How would you test if an element is visible or hidden?
The Problem refers to a single element, You can use this code:
javascript code
// Checks for display:[none|block], ignores visible:[true|false]
$(element).is(":visible");
[ad type=”banner”]
If you change your selector to use jQuery considering you’re using it in other places anyway:
javascript code
if($('#testElement').is(':visible')) { // Code }
Note:
If any one of a target element’s parent elements are hidden, then .is(‘:visible’) on the child will return false
hidden selector:
javascript code
// Matches all elements that are hidden $('element:hidden')
visible selector:
javascript code
// Matches all elements that are visible $('element:visible')
[ad type=”banner”]
The Functions doesn’t work with the visibility attribute.
javascript code
if ( $(element).css('display') == 'none' ) { // element is hidden }
Use the jQuery :visible Selector
html code
<!DOCTYPE html> <html> <head> <title>wikitechy: jQuery Test If an Element is Visible on a Page</title> <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ // show hide paragraph on button click $("p").toggle("slow", function(){ // check paragraph once toggle effect is completed if($("p").is(":visible")){ alert("The paragraph is visible."); } else{ alert("The paragraph is hidden."); } }); }); }); </script> </head> <body> <button type="button">Toggle Paragraph Display</button> <p style="display: none;">Learn to code in wikitechy Tutorial.</p> </body> </html>
To determine whether an element is collapsed or not by using the :visible and :hidden selectors.
javascript code
var isVisible = $('#myDiv').is(':visible'); var isHidden = $('#myDiv').is(':hidden');
you can just include :visible or :hidden in the selector expression
Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.