I am a beginner in javascript and I have seen many people using document.querySelector('#id')
and some people using document.getElementById('id')
for grabbing the html element with the id.
Please answer weather these are same or we have to use them differently.
Asked
Active
Viewed 4,914 times
2

zain
- 416
- 5
- 19
-
1Their results are the same; their speed is implementation-dependent. Related: [Javascript querySelector vs. getElementById](https://stackoverflow.com/q/26848289/4642212). – Sebastian Simon Apr 25 '21 at 04:03
-
in this case of use they do the same. but querySelector methods are more useful, has JS evolve – Mister Jojo Apr 25 '21 at 04:12
-
1Using `querySelector` you can select anything, like elements by name, elements with class name and elements with ids. In above `getElementById` is specifically used for selecting element by ID. https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById. – Sandip Nirmal Apr 25 '21 at 06:15
-
`getelementbyid` only selects id but queryselector selects anything, thats it xD – I_love_vegetables Apr 25 '21 at 08:04
-
1I'm expecting getElementById to be faster by some orders of magnitude, but still resulting in absolute numbers that in 99.9% of cases make absolutely no practical difference. – connexo Mar 26 '22 at 13:43
1 Answers
-1
Quite significant difference is that .getElementById is only applicable on document level while .querySelector can be applied on element level. I.e querySelector allows you to control where to start traversing while getElementById will always traverse from the document root. This means that that querySelector does not require an id to unique within the whole document but only to be unique within a node.

Soren
- 1
-
1Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 08 '23 at 08:36