Home > Article > Web Front-end > Why Does `querySelector` Only Select the First Element and How to Fix It?
Why querySelector Only Selects the First Element and How to Fix It
When using querySelector, it's important to remember that it selects only the first matching element in the document. If you have multiple elements with the same class or ID, only the first one will be returned.
In your case, you have multiple buttons with the same class weekdays representing dates on a calendar. When you click on one of them, it doesn't work because querySelector is only selecting the very first one.
The solution is to use querySelectorAll instead, which returns a node list of all matching elements. You can then iterate over the list and attach event listeners to each one.
Here's the corrected code:
document.querySelectorAll(".weekdays").forEach(elem => elem.addEventListener("click", () => { document.querySelector(".bg-modal").style.display = "flex"; }));
This will attach an event listener to each element with the class weekdays, ensuring that any date can open the form when clicked.
The above is the detailed content of Why Does `querySelector` Only Select the First Element and How to Fix It?. For more information, please follow other related articles on the PHP Chinese website!