Change element’s display to none or block with JavaScript/jQuery
This post will discuss how to change an element’s display to none or block using JavaScript and jQuery.
1. Using JavaScript
In pure JavaScript, you can control the rendering of the container elements using the display attribute. Setting the display to none will not render the element or any of its children, and setting it to block, the browser will render the element.
JS
|
1 2 3 4 5 6 7 |
document.getElementById("hide").onclick = function() { document.getElementById("register").style.display = "none"; } document.getElementById("show").onclick = function() { document.getElementById("register").style.display = "block"; } |
CSS
|
1 2 3 4 5 6 7 8 9 10 |
form { padding: 20px; margin: 10px; border: 1px solid lightgray; } #toggle { padding: 20px; margin: 10px; } |
HTML
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<html> <head> <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> </head> <body> <form id="register"> <div class="form-group"> <label for="email">Email address</label> <input type="email" class="form-control" id="email" placeholder="Enter email"> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" class="form-control" id="password" placeholder="Password"> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> <div id="toggle"> <button type="submit" id="hide" class="btn btn-primary">Hide Form</button> <button type="submit" id="show" class="btn btn-primary">Show Form</button> </div> </body> </html> |
2. Using jQuery
In jQuery, you can use the .hide() and .show() methods to hide or show an element. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 |
$(document).ready(function() { $("#hide").click(function() { $("#register").hide(); }); $("#show").click(function() { $("#register").show(); }); }); |
Alternatively, you can use the .css() method to modify the display attribute, which controls the rendering of container elements.
|
1 2 3 4 5 6 7 8 9 |
$(document).ready(function() { $("#hide").click(function() { $("#register").css("display", "none"); }); $("#show").click(function() { $("#register").css("display", "block"); }); }); |
That’s all about changing the element’s display to none or block using JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)