How To Hide Element By Id In Javascript

In this blog post, we will learn how to hide an element by ID in JavaScript. Hiding elements on a web page can be useful when you want to show or hide specific content based on user interaction or other conditions. JavaScript provides several ways to achieve this, and in this tutorial, we will focus on using the getElementById method and manipulating the element’s style.display property.

Prerequisites

Before we begin, make sure you have a basic understanding of HTML and JavaScript. If you need a refresher, check out these resources:

Using getElementById and style.display

The easiest way to hide an element by ID in JavaScript is by using the getElementById method and changing the element’s style.display property. Here’s a simple example:

<!– HTML –>
<button onclick=”hideElement()”>Hide Element</button>
<div id=”elementToHide”>This is the element we want to hide.</div>

<!– JavaScript –>
<script>
function hideElement() {
var element = document.getElementById(“elementToHide”);
element.style.display = “none”;
}
</script>

In this example, we have a button that calls the hideElement function when clicked. The function retrieves the element with the ID “elementToHide” and sets its style.display property to “none”. This effectively hides the element from view.

Showing the Element Again

To show the hidden element again, you can simply set its style.display property back to its initial value or another appropriate value such as “block”, “inline”, or “inline-block”, depending on the type of element. Here’s an example with two buttons to show and hide the element:

<!– HTML –>
<button onclick=”hideElement()”>Hide Element</button>
<button onclick=”showElement()”>Show Element</button>
<div id=”elementToHide”>This is the element we want to hide and show.</div>

<!– JavaScript –>
<script>
function hideElement() {
var element = document.getElementById(“elementToHide”);
element.style.display = “none”;
}

function showElement() {
var element = document.getElementById(“elementToHide”);
element.style.display = “block”;
}
</script>

With this code, clicking the “Hide Element” button will hide the element, and clicking the “Show Element” button will make the element visible again.

Conclusion

In this tutorial, we learned how to hide an element by ID in JavaScript using the getElementById method and manipulating the element’s style.display property. This technique can be used for various purposes, such as creating interactive web pages or hiding elements based on certain conditions. If you have any questions or suggestions, feel free to leave a comment below. Happy coding!