Difference Between getElementById And querySelector

Difference Between getElementById And querySelector

I recently noticed many people, especially new JavaScript developers, do not know the differences between getElementById And querySelector. The questions that were asked the most are what are the differences and which one is faster. Well the short answer is both of these functions are very similar in what they can do in term of DOM manipulation, but querySelector is more complex and powerful. In this article, I will go over some basic differences between querySelector and selectElementById.

What is getElementById()?

Syntax:

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 null.

What is querySelector()?

Syntax:

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:


<ul>
	<li id="web-id">PHP</li>
	<li>HTML</li>
	<li class="web-class">CSS</li>
	<li class="web-class">JavaScript</li>
</ul>

To get the HTML content of the first li, whose id is web-id, with getElementById:

document.getElementById('web-id').innerHTML;

Now with querySelector:

document.querySelector('#web-id').innerHTML;

getElementById vs querySelector: Difference

What if you want to get the HTML content of the thirdli? You will not be able to use getElementById because there is no id associated with it. But you can so with querySelector.

document.querySelector('ul li.web-class').innerHTML;
Or just simply
document.querySelector('li.web-class').innerHTML;

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 querySelector.

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 querySelector.

You May Also Like