When we are using jQuery in JavaScript, often we want to take an action based on the state of an element. One that is widely used is if the state of the element is visible or not. An element is visible when if it consumes space in the document. Visible elements have a height or width larger than zero.
To find out if an element is hidden, we basically have two tools to use. The first that we’ll see use is: visible.
JavaScript – using: visible with jQuery
The :visible selector checks whether the element is visible within the DOM.
1 2 3 4 5 6 7 8 9 10 |
$ (Document) .ready (function () { if ($ ( "# content") is (. ": visible")) { alert ( 'element is visible in the DOM'); } Else { alert ( 'element is not visible in the DOM'); } }); |
Below we have an example using this selector to determine an action within the program:
1 2 3 4 5 |
<Div id = "countries"> <Div id = "p1"> US </ div> <Div style = "display: none" id = "p2"> Canada </ div> <Div id = "p3"> Mexico </ div> </div> |
To check if the div #countires is visible, use the is () function with the selector “: visible”:
1 2 3 4 5 |
if ($ ( '# countries') is (. ': visible')) { // Is visible, do something Else // Is not visible, do something } |
Loop the visible divs inside the div #countries:
1 2 3 |
$ ( "# Div countries: visible"). Each (function () { document.write ($ (this) .html () '<br />'); }); |
The result will be:
1 2 |
USA Mexico |
JavaScript – using: hidden in jQuery
The :hidden selector perform the opposite check of the previous one. It checks if the element is hidden inside the DOM
1 |
var isHidden = $ ( "#myDiv" ) .is ( ": Hidden" ); |
With these two selectors, you can verify the state of the element and perform something within the code based on the response. Do you know other ways to do this operation in JavaScript? Share your comments in the section below!
If you want to explore other questions, you can check our videos on JavaScript. Below are some examples:
You can also subscribe to some channels that broadcast in JavaScript, such as the following:
Another cool way to find out interesting things about JavaScript is to access our project page!