Can't use querySelectorAll for a single element? [duplicate]

喜夏-厌秋 提交于 2021-02-05 08:46:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!