-3
let buttons = Array.from(document.querySelector('.button'));
// []

let buttons = Array.from(document.getElementsByClassName('button'));
// (20) [div.button, div.button, div.button, div.button, div.button, div.button, div.button, div.button, div.button, div.button, div.button, div.button, div.button, div.button, div.button, div.button, div.button, div.button, div.button, div#equal.button]

Why are the outputs different?

0stone0
  • 34,288
  • 4
  • 39
  • 64
  • 7
    If you want to use `document.querySelector` you should use `document.querySelectorAll` instead for multiple items. – Pablo Silió Jun 22 '22 at 11:19
  • 1
    Additionally, you should not retrieve the elements before they exist. – Teemu Jun 22 '22 at 11:21
  • Probably because the DOM has not ben built when the query is executed. Impossible to tell w/o the html. Anyway, the first line's call would _never_ return more than a single element. – collapsar Jun 22 '22 at 11:25
  • 1
    You're getting a empty array because `Array.from()` converts a DOM element (returned by `querySelector`) to an empty array. Use `querySelectorAll` as @PabloSilió suggested. – 0stone0 Jun 22 '22 at 11:34
  • Thank mate. I got my answer – Sajid Abdullah Jun 22 '22 at 11:36
  • `document.querySelector('.button')` alone ought to have returned a single DOM element. By art of how `Array.from` is specified, an empty array is returned. This can be avoided by strictly constraining the use of `Array.from` to iterables or array-like objects. https://stackoverflow.com/questions/63569627/array-from-mystery – E_net4 Jun 22 '22 at 11:38

1 Answers1

-1

document.querySelector returns a single element.

document.getElementsByClassName returns the list of elements by classname.

If you want to have same output, you should use document.querySelectorAll

AhmerMH
  • 638
  • 7
  • 18