There are various DOM selector like querySelector
, querySelectorAll
, getElementById
, getELementsByClassName
and many more. But my question is when and where we should use which selector during programming. Are there any best practices that tells to specifically use the selector for this task.

- 14,885
- 2
- 14
- 28
-
I think `querySelectorAll` covers them all. So if you need to learn one (and you needn't) then this is it – IT goldman Jul 12 '22 at 14:45
-
1Each has their own purpose. Check out the MDN documentation for them. Here's [`querySelector()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector). The rest are available in the links on the left, or by searching. – Rory McCrossan Jul 12 '22 at 14:45
-
Does this answer your question? [querySelector vs. getElementById](https://stackoverflow.com/questions/26848289/queryselector-vs-getelementbyid) – Brian Scramlin Jul 12 '22 at 14:48
-
What about in context of static node and live node . Is it something to worry about in projects – user10433098 Jul 12 '22 at 14:49
-
1Why have you tagged jQuery? – isherwood Jul 12 '22 at 14:49
-
this is the historical evolution of javascript, with the merging of concepts between css and JS – Mister Jojo Jul 12 '22 at 14:56
2 Answers
querySelector
returns one (the first) element found, and uses a CSS style selector.
querySelectorAll
returns a node list (which, depending on your browser support, you may need to convert to an array to work with), and uses the same CSS style selector.
getElementById
takes a string and only finds an element that matches that ID (IDs should be unique).
getElementsByClassName
takes a string and matches like ID, but can return an array like list of elements.
If you're familiar with CSS selectors, you can use querySelector
and querySelectorAll
for almost every situation. The performance is pretty close to the getElement*
ones, but they're much more powerful. For example, if you wanted to get a span
that is the first child of a class
in an id
, you could do .querySelector('#id .class span')
instead of chaining together .getElementById('id').getElementsByClass('class')[0].getElementsByTagName('span')[0]
.

- 11
- 1
I don't think there's any specific rules on what to use when but I'll share my opinions regarding each method:
- getElementById: Can be used for elements that only exist once and have an id
- getElementsByClassName: For elements that have a class name that can be queried
- querySelector: Use it when you want to query one specific element
- querySelectorAll: same as
querySelector
but for multiple elements
caniuse.com is a great resource to check browser support.

- 174
- 4
- 13
-
1Honestly, `getElementById` and `getElementsByClassName` are both very commonly used. Also, there's no official statement saying that those elements are legacy. – mollthecoder Jul 12 '22 at 14:55
-