1

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);
AlwaysLearning
  • 311
  • 4
  • 12
  • 1
    `document.querySelectorAll(".top")[0] === document.querySelector(".top")` - the former returns an array-like object, the latter returns a single item. – Ryan Wheale Feb 14 '17 at 04:34
  • See also [Expand an iterable element or non-iterable element into an array without checking element .length](http://stackoverflow.com/questions/40198807/expand-an-iterable-element-or-non-iterable-element-into-an-array-without-checkin) – guest271314 Feb 14 '17 at 04:50

1 Answers1

5

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);
Dan Lowe
  • 51,713
  • 20
  • 123
  • 112
  • 1
    ... which is the *entire* reason why the guidance is to use querySelector when you know you have only one element to work with. – BoltClock Feb 14 '17 at 04:38
  • 1
    OMG, of course. I actually know this but missed it. Total brain fart. I would delete this question out of embarrassment but others may have the same brain fart someday. LOL – AlwaysLearning Feb 14 '17 at 04:56