The first difference between the two methods is the type they return
document.querySelectorAll(".clase")
returns a static list NodeList of elements
This means that the changes made to the DOM then NO will be reflected in the content of the list.
document.getElementsByClassName("clase")
returns a viva HTMLCollection collection of items by what any change to the DOM will automatically update its content. This means that new items may appear or be removed from the list when classes are added or removed.
In terms of efficiency I do not think there is much difference. There is a note for querySelectorAll
and it is that it searches using a algorithm first in depth and in pre-order of the nodes in the document.
Transverse DOM is always a costly process, which I think if it will make it more efficient is from where you start looking as both methods allow you to change the start of the search using
// Ambos comenzarán a buscar a partir de element
element.querySelectorAll(".clase");
element.getElementsByClassName("clase");
My recommendation of one over another:
-
If you want to select items using any CSS selector, operate them and then discard that selection using querySelectorAll
-
To observe element sets use getElementsByClassName