A <div> element is often used as a container and it will have many other elements, like a form. You might want to show or hide the <div> element when certain conditions are fulfilled.
Here’s a common scenario. I wish to toggle a <div> element on button click.
The Markup and the Script
<html> <head> <title>Toggle example using Pure JavaScript</title> </head> <body> <p> <input type="button" value="Show DIV" id="bt" onclick="toggle(this)"> </p> <!--The DIV element to toggle visibility. Its "display" property is set as "none". --> <div style="border:solid 1px #ddd; padding:10px; display:none;" id="cont"> <div> <label>Name:</label> <div><input id="name" name="yourname" /></div> </div> <div> <label>Age:</label> <div><input name="age" id="yourage" /></div></div> <div> <label>Additional Information (optional):</label> <div><textarea style="width:100%;" rows="5" cols="46"></textarea></div> </div> </div> </body> <script> function toggle(ele) { var cont = document.getElementById('cont'); if (cont.style.display == 'block') { cont.style.display = 'none'; document.getElementById(ele.id).value = 'Show DIV'; } else { cont.style.display = 'block'; document.getElementById(ele.id).value = 'Hide DIV'; } } </script> </html>
A simple if-else condition in your JS code will do the trick. In the above example, I am changing the element’s display property on button click.
You can further simplify the above code using a ternary operator. For example,
<script> function toggle(ele) { var cont = document.getElementById('cont'); cont.style.display = cont.style.display == 'none' ? 'block' : 'none'; } </html>
I have shared a similar example in Angular too.
Not just on button click, you can change the visibility of an element based on other conditions, like toggling the <div> element when someone select or un-select a value in SELECT dropdown list, etc.