There are a few semantic issues with your JavaScript that I see. For example, a
getElementById
would return a single element, then why use a forEach? If your HTML has multiple elements with the ID, then the HTML is invalid — but JavaScript will still return a single element.
Please see this:
Document.getElementById() - Web APIs | MDN[
^]
Secondly, the
forEach
method (focus on the word method) does not have a ".data-selected" field — unless, of course, you added on. That is why it would not work.
Please see this:
Array.prototype.forEach() - JavaScript | MDN[
^]
Also, in JavaScript, you can access the element properties using the index notation as well, like:
if (bttns["data-selected"] == false) {
The syntax that you are using would be considered as if you are trying to access the
data
field on
bttns
object and then subtracting the
selected
variable, and then ... You see where I am going?
There are a lot of areas that you need to improve there in the code, but since you asked the question about the event listener functions, I don't see that would be an issue. If I had to write this code, I would — apart from writing this code in a component-fashion — simply add a method that would handle everything for me.
Introduction to events - Learn web development | MDN[
^]
Pass the object to the method and then operate on it. Instead of querying and then reading a property to mutate another property.