GetElementById vs. querySelector: Which is better and why use one over the other?
Which is better – getElementById or querySelector? Well, better is a very subjective answer. Both getElementById and querySelector are an element-grabbing method from the JavaScript Document Object Model (DOM), so with each method, you can pick up whatever element you want to manipulate with, of course depending on the circumstances. The advantage at least is that you don’t have to choose which one you’ll use – both, GetElementById and querySelector method have their own use cases and you can choose methods interchangeably. However, the question remains – why use one over the other? So, let’s dive in.
When should you use getElementById()?
In JavaScript you will often have to search and manipulate HTML elements and to do so you’ll have to find one first. getElementById method will retrieve an element with a specific ID attribute, hence the name. Compared to the querySelector method, which we will take a look at in a second, getElementById method is much more restrictive because you can only fetch elements based on their particular ID or tag name (for getElementsByTagName), or class name (for getElementsByClassName). As the name declares, getElementBy… methods have a slightly more semantic approach because they read well in terms of what exactly you’re doing with your code – you are trying to get an element(s) based on its ID, class name, or tag name.
The basic syntax of getElementById looks like this:
var el = document.getElementById(id);
And, in the code, getElementById looks like this:
<!-- this is a HTML code from which you will retrieve an specific element -->
<div>
<div id="shop-id">The shop</div>
<div>A bit of description</div>
<div class="shop-contact">Address</div>
<div class="shop-contact">Phone: 00335577</div>
<script>
// select an element from the HTML - the ID of that element is "shop-id"
var el = document.getElementById("shop-id");
</script>
As already said above, getElementById method is much more limited in the scope or freedom of action, because you can only retrieve elements based on their specific ID.
What if the element you want to fetch doesn’t have an ID?
You would have to assign an ID to that element solely for the purpose of retrieving it. And, if you decide not to assign an ID, or if the element with the specified ID is not in the document, the getElementById method will return null.
And what if you want to retrieve more than one element from the DOM?
Because of the restrictiveness of the getElementById – one element can have one specific ID – getElementById method will not yield proper results. And this is the exact part where querySelector and querySelectorAll come in very handy.
When should you use querySelector?
Before we take a look at a simple example of how querySelector looks in the code, let’s take a look at the theory behind it. Yaaay. More JavaScript theory.
querySelector is newer. It all started with jQuery and when developers of the library noticed the method is becoming more and more popular, they decided to include it in the JavaScript update. Although all major browsers support it (it’s not that new), there could be issues if you’re using an older browser or a less supported one. In this case, getElementById may be more suitable for your purposes. In addition, getElementById is faster – some sources claim even up to 30 % faster.
In terms of semantics, similar to the getElementBy method, the querySelector method also states that you are selecting something from a query and from there exactly the query itself is dependant on the argument you’re passing.
In terms of handling and functionality, compared to the getElementById method where you don’t have to specifically tell that you’re looking for an id in the document because the id is in the name and the entire functionality of the method, with querySelector you’re using CSS selectors as an “element of selection”. Therefore you have to use a hashtag (#) to specify that it’s an ID you’re looking for and that’s the key difference. If you would be looking for a class, you would use a dot (.). In the example we already applied above, that would look like this:
// # specifies that it's an id you're looking for
var el = document.querySelector('#shop-id');
The getElementBy… is capable of grabbing any element that has an id or a class or a tag assigned, but a querySelector is so much more powerful because it is driven the same way CSS selectors are and you can even chain your selectors just like in CSS. Oh man, you can grab so much more with so much less assignment. I hope that gives you an idea as to what that might mean in terms of scope of power.
Let’s take a look at a bit more “complex” examples below.
What if you want to get the HTML content of the third div? You will not be able to use getElementById because there is no id associated with it. (Tip: You could however use getElementsByClass although that would return all div elements with that same class name, or as already said in the section where we explain getElementById you could assign an ID to the element you want to catch, of course solely for the purpose of catching it). So, a more elegant solution, in this case, would be the querySelector method. In general, querySelector is a lot less clunky method, especially if you’re digging into the DOM tree and looking for a node inside a node, inside a node.
var el = document.querySelector('div div.shop-contact');
// or just simply
var el = document.querySelector('div.shop-contact');
The example above will give you the third div element. But what if you want the fourth one? What if you want all content under some deeply nested div without class or id? Well, yes, querySelector does not have superpowers. querySelector will grab the first element that meets your criteria, so if there are more elements that meet your criteria, with querySelector you can forget about the second or third (or so on) element. However, there is a solution to it and it’s called querySelectorAll. This method almost resembles the querySelector, but compared to the latter that will return the first element that meets the criteria you listed, querySelectorAll will grab ALL elements that meet your selector.
So, with the querySelector and querySelectorAll methods you use selectors that are actually comma-separated CSS selectors and you target elements within the document the same way you would target them using a style rule. Good luck and happy coding.