Sobes.tech
Junior

What is the difference between the methods .getElementsByClassName and .querySelectorAll?

sobes.tech AI

Answer from AI

getElementsByClassName returns a live collection of HTMLCollection elements with the specified class. Changes in the DOM are automatically reflected in the collection. This method is only available for elements and the document.

querySelectorAll returns a static collection of NodeList of all elements matching the CSS selector (or group of selectors). Changes in the DOM after calling the method do not affect the returned collection. This method is available for elements, the document, and document fragments.

Main differences:

Attribute getElementsByClassName querySelectorAll
Return type HTMLCollection NodeList
Collection type Live Static
Argument Class name (string) CSS selector (string)
Availability Element, Document Element, Document, DocumentFragment
Support Wide Depends on the selector
// getElementsByClassName
const elementsByClass = document.getElementsByClassName('my-class');
// changes to DOM will affect elementsByClass

// querySelectorAll
const elementsBySelector = document.querySelectorAll('.my-class, #my-id');
// changes to DOM will NOT affect elementsBySelector