One Function To Fire On Same Class Elements Click
I'm trying to make controls for category list with sub-category and sub-sub-category lists. Here's HTML:
- Category&
Solution 1:
As others have already mentioned, you can't stack multiple elements with the same ID since
document.getElementById()
is not supposed to return more than one value.You may try instead to assign the "trigger" class to each of those spans instead of IDs and then try the following code
var triggers = document.getElementsByClassName("trigger"); functionsubCatStatus() { if(this.parentElement.children[1].className != "... expanded") { this.parentElement.children[1].className += " expanded" } else { this.parentElement.children[1].className == "..." }; }; for(var i = 0; i < triggers.length; i++) { triggers[i].addEventListener("click", subCatStatus); }
Solution 2:
javascript getElementById returns only single element so it will only work with your first found element with the ID.
getElementsByClassName returns an array of found elements with the same class, so when adding listener to the event on element you would require to loop through this array and add individually to it.
Post a Comment for "One Function To Fire On Same Class Elements Click"