JavaScript JavaScript and the DOM Traversing the DOM Getting the First and Last Child

Daniel Grieve
Daniel Grieve
6,429 Points

querySelector result vs getElementByClassName result

During the extra-credit task to disable the up/down buttons I came across a discrepancy between querySelector and getElementByClassName methods. Putting these into the console I get the following result...

links[0].querySelector('.up');
<button class=​"up" disabled style=​"background-color:​ lightgrey;​">​up​</button>links[0].getElementsByClassName('.up');
HTMLCollection []length: 0__proto__: HTMLCollection

I don't understand why one would retrieve the button I want vs the other which returns an empty HTML collection. My variables are defined as...

const listUl = document.querySelector('ul');
const links = listUl.children;

2 Answers

links[0].getElementsByClassName('.up');

When you use method "getElementsByClassName" you do not need to provide "." (dot) Dot is a representation of class when using querySelector because querySelector can be used to target id's too using #

Same as you don't provide # when using getElementById you don't need to add "." when targeting class using getElementsByClassName.

Additional note: getElementsByClassName returns collection of elements with targeted class, just like querySelectorAll, so you will need to access targeted element with index position [0] or so.

andren
andren
28,359 Points

The querySelector expects a CSS selector as the criteria to search for, while getElementsByClassName expects the name of the class you are searching for. Since you passed .up (which is a valid CSS selector, but not actually the name of the class) to both of the methods only the querySelector found the element you were searching for.

And the querySelector always returns a single element, even if multiple ones are found one the page. The getElementsByClassName is pretty much the opposite, it will always returns a collection of HTML elements, even if only one or fewer elements is found matching your criteria.

That is the reason for the difference in types being returned.

If you pass the class name to getElementsByClassName like this:

links[0].getElementsByClassName('up'); // Removed dot in beginning of string

Then you would get a collection containing the element you where looking for.

Daniel Grieve
Daniel Grieve
6,429 Points

Thank you for the reply!