To toggle the visibility of an HTML element using JavaScript, you can use the style
property of the element and change its display
property between "none" and "block". Here's an example:
HTML:
<button onclick="toggleVisibility()">Toggle Element</button>
<div id="myElement">This is the element to toggle</div>
JavaScript:
function toggleVisibility() {
var element = document.getElementById("myElement");
if (element.style.display === "none") {
element.style.display = "block";
} else {
element.style.display = "none";
}
}
In this example, we have a button with an onclick
event that triggers the toggleVisibility
function. The toggleVisibility
function fetches the element with the myElement
id using document.getElementById
.
Then, it checks the current value of the display
style property of the element. If it is "none", it changes it to "block" to make the element visible. If it is not "none" (which means it is visible), it changes it to "none" to hide the element.