How do you add expand and collapse in HTML?

Using JavaScript

Expand and collapse can be achieved in HTML by using the combination of JavaScript and HTML.

Writing Javascript Code

To create an expand and collapse action in HTML, you need to write a small JavaScript code and insert it in the HTML page. The code should include two functions with the same name. One function to expand the content and another to collapse it.

The first function should have an “if-else” condition. When the user clicks on the link, the condition should check whether the content is already expanded or not. If the content is already expanded, it should hide the content by changing the style property of the element to “none”. If the content is not expanded, it should show the content by changing the style property of the element to “block”.

Adding HTML Elements

To add the expand and collapse element, you need to add two HTML elements. The first one is a link with the id “expand”, and the second one is a div with the id “content”. The div should contain the content that you want to expand and collapse.

The link should have an onclick event, which calls the JavaScript function that you have written earlier. When the user clicks on the link, the JavaScript function will be executed and the content will be expanded or collapsed, depending on the condition.

Adding the Javascript Code

Finally, you need to insert the JavaScript code into the HTML page by using the