Home > Article > Web Front-end > Why does querySelector only select the first element when using querySelectorAll()?
Why does querySelector only select the first element and how can I fix this?
When the querySelectorAll() method is used on a selector that selects multiple elements, it returns a list of nodes.
In the provided code, you are using querySelectorAll() to select all elements with the class "weekdays." The issue is that you are using querySelector() later in the code to add an event listener to each element in the list, which only targets the first element in the list.
To fix this issue, you should use forEach() to iterate over each element in the list and add the event listener to each element.
Here is the updated code:
document.querySelectorAll(".weekdays").forEach(elem => elem.addEventListener("click", () => { document.querySelector(".bg-modal").style.display = "flex"; }));
The above is the detailed content of Why does querySelector only select the first element when using querySelectorAll()?. For more information, please follow other related articles on the PHP Chinese website!