Difference Between getElementById And querySelector
What is getElementById()?
element = document.getElementById(id);
Returns a reference to the element by its ID. If the element with the specified ID is not in the document, it will returns
What is querySelector()?
element = document.querySelector(selectors);
Returns the first element within the document that matches the specified group of selectors, or null if no matches are found.
getElementById vs querySelector: Similarly
To help you understand better, please look at the following example:
To get the HTML content of the first
li, whose id is web-id, with
getElementById vs querySelector: Difference
What if you want to get the HTML content of the third
li? You will not be able to use
getElementById because there is no id associated with it. But you can so with
Or just simply
getElementById vs querySelector: Performance
I can probably write a book on the performance differences between these two functions. But for now all you need to know is this,
getElementById is faster and better supported than
Should You Use getElementById or querySelector?
Both of these functions are powerful but you must decide which one better suits your need. I almost always use
getElementById instead of
querySelector, but don’t let me discourage you from using
querySelector. If you have a complicated page and you do not want to add id over all it, then use