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 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
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*, 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
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 =)
Soft skills are as critical as technical skills for a software engineer. No one works in isolation. Each person has to deal with teammates, colleagues, managers, etc. Therefore team interpersonal skills are essential too. Soft skills include things like good communication, honesty, teamwork, integrity, organization, empathy, etc.