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 934 times
1
zain
- 316
- 2
- 11
-
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
0
When you use getElementById to assign a variable, you don't have to declare that you're looking for an id in the document because it's already in the method's name and functionality. When you perform the same thing with querySelector, though, you're using CSS selectors, so you'll need to add the # to indicate that you're looking for an id, and that's the key difference.
const container = document.getElementById("container")
vs
const banner = document.querySelector("#banner")
Initially both do the same thing.
Dinindu Gunathilaka
- 314
- 2
- 13