Software Developer

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".

 

By

We've 2 Responses

Leave a Reply to Alex Cancel reply

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

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

[code]

YOUR CODE HERE 

[/code]