Tom Smykowski
1 min readFeb 21, 2022

--

I am not sure if getElementById and getElementByClassName are more readable. Both methods have same 12 characters making it harder to distinguish between them. Comparably query Selector indicates I will grab something from the DOM. While I have to look only at one, nicely exposed sign to differentiate: dot or hash.

Also from the maintainability perspective query Selector is nicer option because I don't have to change method to change the query. Often I have to change Id selector to class selector or expand class selector to choose more specific elements. In these cases eventually I have to use querySelector anyways.

To sum it up for me, querySelector is the default one because it is easier to read and maintain.

If it comes to speed it does not matter so much in most cases. It may have impact on list heavy pages. And in these cases optimisation would be to split data into more pages, introduce filtering etc. before going into such kind of optimisation. Otherwise it would be premature optimisation over readability and maintainability.

So yeah. querySelector awesome. Use querySelector

--

--

Tom Smykowski
Tom Smykowski

Written by Tom Smykowski

🚀 Senior/Lead Frontend Engineer | Angular · Vue.js · React | Design Systems, UI/UX | Looking for a new project! 📩 contact@tomasz-smykowski.com

No responses yet