Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between getElementsByClassName and querySelectorAll? [duplicate]

Tags:

javascript

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?

like image 266
user1778856 Avatar asked May 27 '15 04:05

user1778856


People also ask

What is the difference between getElementsByClassName and querySelectorAll?

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.

What is a difference between the querySelector and querySelectorAll methods?

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.

What does querySelectorAll mean?

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.

Is getElementsByClassName faster than querySelector?

Specifically, getElementById() and getElementsByClassName() are more than twice as fast as querySelector() and querySelectorAll() .


1 Answers

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.

like image 55
Anirudha Avatar answered Sep 21 '22 17:09

Anirudha