I am looking to dynamically toggle the class "collapsed" on each element with the class "category" when it is clicked. The issue arises when these "category" elements are nested within each other, causing the child elements to also trigger the class change on their parent elements.
For instance
Here's an example of the HTML structure:
<div class="category">
<div class="category">
<div class="category"></div>
</div>
</div>
<div class="category">
<div class="category"></div>
</div>
This snippet of JavaScript accomplishes the task:
var categories = document.getElementsByClassName("category");
for (var i = 0; i < categories.length; i++) {
categories[i].addEventListener("click", function () {
this.classList.toggle("collapsed");
});
}
However, a problem occurs when clicking on a nested element because the "this" selector will affect not only the current element but also its parent elements with the "category" class.