问题
I understand that under normal circumstances, you would use querySelector to select a single element and querySelectorAll for multiple. However, I was surprised to discover that querySelectorAll doesn't work with a single element. I expected it to work with one OR more. I can't find anything that says it shouldn't work with just one so I'm asking here if that's normal and according to spec?
HTML:
<div class="top container">
<div class="pod" draggable="true">big</div>
<div class="pod" draggable="true">small</div>
<div class="pod" draggable="true">happy</div>
<div class="pod" draggable="true">rich</div>
<div class="pod" draggable="true">fast</div>
</div>
JS:
function dragStart(e) {
console.log("drag started");
e.target.style.opacity = "0.5";
}
Works with this (dragStart function is called):
var topPods = document.querySelector(".top");
topPods.addEventListener("dragstart", dragStart);
But doesn't work with this (dragStart function not called):
var topPods = document.querySelectorAll(".top");
topPods.addEventListener("dragstart", dragStart);
回答1:
querySelectorAll
returns a NodeList, not a single element (even if the result of the query is only one element). So you are trying to attach an event listener to that NodeList, not to an element.
This does work (note the [0]
):
var topPods = document.querySelectorAll(".top");
topPods[0].addEventListener("dragstart", dragStart);
来源:https://stackoverflow.com/questions/42217873/cant-use-queryselectorall-for-a-single-element