I am designing this menu and as you can see, there are buttons that have submenus, when you click the button with the menu icon (The 3 bars) the menu is hidden and only the menu icons are seen (The circles) But since it has sub menus, I try to make that when the menu is closed and they click on the element a
that would open a submenu, it also executes the function JS
that opens the entire menu to be able to visualize it. The problem is that when I give it addEventListener('click')
this it only works with the first sub menu. The others is as if the event was not assigned to them.
document.getElementById("open").addEventListener("click", open_menu);
function open_menu(){
body.classList.add("body_move");
side_menu.classList.add("menu__side_move");
}
This is the event and the function
<a href="#" class="nav__link" id="open"><i class="far fa-circle"></i> Servicios</a>
And this is the element. They all have the same id
but it only works with the first one, the others do not recognize the event, BUT, if I put the ´onclick=('open_menu()')´ directly there, it works. I could use the onclick and put it on each 'a' element that needs it, but it doesn't seem like a good practice and I also want to know why it only executes on the first one.
Ok, so if I understood correctly your problem is that the onclick only works with the first element.
There are two things here.
You shouldn't use the click event directly on html elements, it's bad practice as your code doesn't become very maintainable
The id is unique, you shouldn't put the same one for each element, it's just a bad practice. Use a class instead. So it would be like this:
In order to make each element have this click event, you must select all of them, not just one, since when you do a getElementById('open') you are only referring to the first element JS finds. You must choose them all. So taking into account the correction that I mentioned about not putting the same id to several elements, for it to work you must do it in the following way:
What we are doing here is that with the querySelectorAll we select all the elements that have the .open class. These elements will be stored in an array, so we iterate over them with a forEach and assign each element the click event.