How to Hide or Show Elements using JavaScript
Table of Contents
Sometimes, you want to be able to programmatically control whether an element is visible or not.
In this post, we'll learn how to hide and show DOM elements using JavaScript.
For this post, we'll be using the following HTML:
HTML<div class="content">
This is content
</div>
Now, we'll create a button that will toggle the visibility of the element.
HTML<button class="toggle-content">
Toggle Content
</button>
Add a click listener to the button that will call a method to toggle the visibility of the element.
HTML<button class="toggle-content" onclick="toggleVisibility()">
Toggle Content
</button>
Create a method called toggleVisibility that will toggle the visibility of the element.
We will take advantage of the display
CSS property to accomplish this.
JAVASCRIPTconst toggleVisibility = () => {
const element = document.querySelector(".content");
if (element.style.display === "none") {
element.style.display = "block";
} else {
element.style.display = "none";
}
}
Here's a full-page working example:
HTML<!DOCTYPE html>
<html>
<body>
<div class="container">
<div class="content">
This is content
</div>
<button class="toggle-content" onclick="toggleVisibility()">
Toggle Content
</button>
</div>
<script>
const toggleVisibility = () => {
const element = document.querySelector(".content");
if (element.style.display === "none") {
element.style.display = "block";
} else {
element.style.display = "none";
}
}
</script>
</body>
</html>
Test it out for yourself:
- HTML
- JavaScript
And there you have it, you are now showing and hiding a DOM element using JavaScript!
Conclusion
In this post, we learned how to programmatically hide and show DOM elements using JavaScript.
We used the display
property and created a simple function to toggle between the two states.
Hopefully, you've found this post helpful and have enjoyed reading it!
- Getting Started with Svelte
- Getting Started with Express
- Getting Started with Electron
- How to deploy a .NET app using Docker
- How to build a Discord bot using TypeScript
- How to deploy a MySQL Server using Docker
- How to deploy a Node app using Docker
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Learn how to build a Slack Bot using Node.js
- Creating a Twitter bot with Node.js
- Using Push.js to Display Web Browser Notifications
- Using Axios to Pull Data from a REST API