Hide and Show HTML tag with JavaScript


How to toggle the display of HTML section using JavaScript?

We can apply the CSS effect on the HTML section using JavaScript. So we can apply any CSS property to the HTML tag or section. Using button on click we are interested to perform following events.

  1. Now we are going to hide the section if the section is not hide.
  2. And similarly, if hide then show the section.

hide show using javascriptShow and Hide HTML section using Button
We want to hide and show the following paragraph. <p id='myparagraph'> Courtesies cannot be borrowed like snow shovels; you must have some of your own. </p>

JavaScript function to Hide and show the Paragraph

<script type="text/javascript"> function showhide() { paragraph = document.getElementsByTagName('p')[0]; if (paragraph.style.display === "none") // Currently is Hide { paragraph.style.display = "block"; // To Show } else // Currently is Show { paragraph.style.display = "none"; // To Hide } } </script>

Output of Hide and Show Paragraph Using JavaScript

Courtesies cannot be borrowed like snow shovels; you must have some of your own.

Source code of hide and show effect using JavaScript

<button onclick="showhide()"> Click me to Hide & Show </button> <p id='myparagraph'> Courtesies cannot be borrowed like snow shovels; you must have some of your own. </p> <script type="text/javascript"> function showhide() { paragraph = document.getElementById('myparagraph'); if (paragraph.style.display === "none") // Currently is Hide { paragraph.style.display = "block"; // To Show } else // Currently is Show { paragraph.style.display = "none"; // To Hide } } </script>
Chapter Next »