In this tutorial, you will learn how to show hide (toggle) elements using JavaScript.
JavaScript Example to Show-Hide (toggle) Elements on Click of a Button
The following program will create a paragraph and a button, and on click of the button it will show or hide the paragraph element.
The script for the HTML HEAD part:
<style> #msg { background-color: #ffff00; font-weight: bold; } #msg[aria-hidden="true"] { display: none; } </style> <script> window.onload=function() { document.getElementById("button1").onclick=hideshow; document.getElementById("msg").setAttribute("aria-hidden","true"); } function hideshow() { var msg = document.getElementById("msg"); var hidden = msg.getAttribute("aria-hidden"); if (hidden == "true") { msg.setAttribute("aria-hidden", "false"); } else { msg.setAttribute("aria-hidden", "true"); } } </script>
The code for the HTML BODY part:
<div id="msg"> <p> Click the button again to hide this paragraph. </p> </div> <button id="button1">Hide/Show</button>
Output
The output would be as shown in the featured image of this tutorial.