简体   繁体   中英

Can't use querySelectorAll for a single element?

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);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM