1. Overview
Challenge & starter files: Advent of JS
Full codes: nilstarbb/advent-of-js/11-accordions
Live Demo: 11 - Accordions || Advent of JavaScript
Preview:
2. Details
Users should be able to:
- Click on a collapsed question to expand it and view the answer.
- Click on a collapsed answer to collapse it and hide the answer.
3. Coding
Coding logic:
- Toggle the
expand
class inli
element when clicking the question. - Toggle every other
expand
class in otherli
elements.
Please do not use arrow functions when you need to use this
to refer to the current element. Arrow functions don’t have their own this/super/arguments
binding. They inherit them from their parent lexical scope.
Code:
const lists = document.getElementsByTagName("li");
for (let i = 0; i < lists.length; i++) {
lists[i].addEventListener("click", function () {
this.classList.toggle("expand");
for (let j = 0; j < lists.length; j++) {
if (j != i) {
lists[j].classList.remove("expand");
}
}
});
}