In JavaScript, the querySelector method selects the first matching element in the document based on the provided selector string. If multiple elements match the selector, only the first one is returned.
In your provided CodePen, you're using querySelector to select the elements with the class weekdays. However, you observe that only the first matching element triggers the click event, while all others do not.
To address this issue, you should use the querySelectorAll method instead, which returns a NodeList containing all the matching elements. Then, you can iterate over the NodeList and attach the event handler to each element.
document.querySelectorAll(".weekdays").forEach(elem => { elem.addEventListener("click", () => { document.querySelector(".bg-modal").style.display = "flex"; }); });
Now, when you click on any weekdays element, the modal will properly appear, fixing the issue you were experiencing with querySelector only selecting the first element.
The above is the detailed content of Why is `querySelector` Selecting Only the First Element and How Can I Fix This?. For more information, please follow other related articles on the PHP Chinese website!