Home > Web Front-end > CSS Tutorial > Why Does `querySelector` Only Select the First Element and How to Fix It?

Why Does `querySelector` Only Select the First Element and How to Fix It?

Susan Sarandon
Release: 2024-11-06 00:06:02
Original
329 people have browsed it

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";
}));
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template