Toggle Show/Hide Multiple Elements With Pure JavaScript

This is for when you need to toggle between showing and hiding more than one element on a page. For example, click a heading to show a list underneath it, then click again to hide the list. This uses pure JavaScript, no jQuery or other libraries. (See this instead for an example using jQuery.)

You want the event listener to apply to many items, for example, to all the h2 elements on the page. You don’t need to add the event listener multiple times to each element. You add the event listener once, which checks if an h2 element was clicked.

Here is a working example. In this example, the h2 headings have the class "clickable-heading".


See more:


We've 5 Responses

  1. March 31st, 2021 at 3:40 am

    when i an using this code it dint work and sowing this error in console

    Uncaught TypeError: Cannot read property ‘style’ of null
    at HTMLDocument.toggleDocs


Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this: