From my understanding,
var elems = document.querySelectorAll(".class");
var elems = document.getElementsByClassName("class");
should return the same things. However, when I try to remove the class from all the elements using
for (var i = 0; i < elems.length; ++i)
elems[i].className = "";
I get different results. querySelectorAll
successfully removes the classes from all the elements, but getElementsByClassName
only removes the classes from about half the elements.
What's going on?
getElementsByClassName returns a collection of elements while query selector returns only one element. You can access the element you want inside the collection by using bracket notation.
Differences: As seen above, querySelector() methodcan only be used to access a single element while querySelectorAll() method can be used to access all elements which match with a specified CSS selector. To return all matches, querySelectorAll has to be used, while to return a single match, querySelector is used.
The querySelectorAll() method in HTML is used to return a collection of an element's child elements that match a specified CSS selector(s), as a static NodeList object. The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers.
Specifically, getElementById() and getElementsByClassName() are more than twice as fast as querySelector() and querySelectorAll() .
querySelectorAll
doesn't return live DOM elements. Subsequent changes to the structure of the underlying document won't be reflected in the NodeList object returned by querySelectorAll
. This means that the object will instead contain a list of matching Element nodes that were in the document at the time the list was created.
getElementsByClassName
returns live DOM elements. Any subsequent change made to those DOM elements would be reflected in the list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With