As the old adage goes– you can do a million things a million ways in JavaScript.
One of those million things is to select a JavaScript element. The main ways you're probably familiar with are by using:
- querySelector
- querySelectorAll
- getElementById
- getElementsByTagName
- getElementByClassName
- getElementsByName
The first difference is obviously breadth. While querySelector* can obviously select either the first or all matching elements, getElement* has at least four options across two conventions– getElement vs getElements.
The main difference (and the reason I wanted to write this blog) is that querySelectorAll and getElements* return different values.
querySelectorAll
- querySelectorAll returns a non-live NodeList containing one Element object for each element that matches at least one of the specified selectors or an empty NodeList in case of no matches. (MDN)
- This is great because you can treat this node list like any array and use array methods like
forEach()
.
Below is an example of what this would look like in practice:
let content = document.querySelectorAll(".content") // undefined
content // NodeList(3) [div.content, div.content, div.content]
content.forEach(node => console.log(1)) // 1, 1, 1
As you can see above, the return value of content
is an array containing three items.
getElements
- getElements*, on the other hand, returns a live HTMLCollection of found elements.(MDN)
- Though it has square brackets like the NodeList, it does not have access to array methods like
forEach()
.
let collection = document.getElementsByClassName("content") // undefined
collection // HTMLCollection(3) [div.content, div.content, div.content]
collection.forEach(x=> console.log(x))
VM1771:1 Uncaught TypeError: collection.forEach is not a function
at <anonymous>:1:12
For beginners, I would say– default to using querySelector and querySelectorAll because do will avoid some of the pitfalls I outlined above.
While writing this blog post I briefly looked up videos from my favorite YouTubers and this one seemed like a keeper.
Hope you find it helpful =)