- Create a nested HTML div tag with class names containing the questions and answers.
- For styling, add some CSS properties like alignment, font size, padding, margin, etc.
HTML Code: We have used classes for questions and answers. These classes are used for styling purposes.
CSS Code: For styling, we have used CSS properties.
Note: We can also create another file for styling or we can add them in the same HTML file under the style tag.
We have used a forEach() method to call the function over each element in the answer variable. Now, specify an event listener addEventListener(), when the element is clicked. It will check if the event has an active class by using the classList property which returns the names of all the classes associated with that element or event.
If it has the active class, that means it is showing the answer or accordion is in an expanded state, then we will remove the active class from that event to hide the content. If it does not have an active class, that means the accordion is in the collapsed state, then we will add an active class.
Complete Code: In this section, we will combine all the codes together to create the FAQ