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.
The :visible selector checks whether the element is visible within the DOM.
$ (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:
<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”:
if ($ ( '# countries') is (. ': visible')) { // Is visible, do something Else // Is not visible, do something }
Loop the visible divs inside the div #countries:
$ ( "# Div countries: visible"). Each (function () { document.write ($ (this) .html () '<br />'); });
The result will be:
USA Mexico
The :hidden selector perform the opposite check of the previous one. It checks if the element is hidden inside the DOM
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!
We’re thrilled to announce an exciting opportunity for you to win not one but two…
Acquiring practical skills is crucial for career advancement and personal growth. Education Ecosystem stands out…
Artificial Intelligence (AI) has been making significant strides in various industries, and the software development…
Another week to bring you the top yield platforms for three of the most prominent…
If you hold a large volume of LEDU tokens above 1 million units and wish…
It’s another week and like always we have to explore the top yield platforms for…
View Comments
This was brilliantly done thanks. (Y)