Why does querySelector only select the first element when using querySelectorAll()?

Linda Hamilton
Release: 2024-11-07 08:17:02
Original
518 people have browsed it

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!