When to use querySelector instead of getElementById?

Asked

Viewed 7,037 times

5

I looked for some information on the internet about this already, including in Soen, however I could not reach an exact conclusion.

I must point out that the issue is not only about performance, but about unusual situations and good practices.

Anyway. Do

document.getElementById('teste');

or

document.querySelector("#teste");

returns the same thing. I know that the getElementById is approximately 5x faster, but I believe there are situations where the use of querySelector would be better. Readability perhaps?

If getElementById is faster, in which situations the querySelector if it proves a better option?

Note: the question refers only to the capture case of Ids.

  • 3

    Out of curiosity: why the getElementById is approx. 5x faster? Is there anywhere I can see about this? I even imagine that there should be another separate structure with the ids, but I see no reason for querySelector not make use of this structure being that one can easily identify when the selector is an id.

  • 2

    getElementById vs. getElementsByClassName vs. querySelector vs. jQuery executed in my browser: https://i.stack.Imgur.com/2ZA2u.png. Nothing absolute, but are some numbers.

  • 1

    "I know getElementById is about 5x faster" - Have some source / benchmarks to support this statement ?

  • @Isac I have read this in some places, including in Soen: https://stackoverflow.com/questions/15046356/performance-using-js-queryselector , but I cannot claim to be a totally reliable source, so be free to correct me.

1 answer

15


In addition to the performance involved (getElementById is a bit more performatic, I will quote some tests below) we can consider:

Queryselector

The advantage of its use, as opposed to document.getElementById, document.querySelector can return classes, in addition, it is possible to use seletores CSS, what cannot be done with the getElementById.

Example:

document.querySelector("#element a[target]");

document.querySelector("#element a[target]").style.color = 'green';
<span id="element"> <a href="#" target="_blank"> link com target </a> </span>

How about a more advanced selection?

document.querySelector("#element ul li:nth-child(2)").style.color = "blue";

document.querySelector("#element ul li:nth-child(2)").style.color = "blue";
<div id="element">
    <ul>
        <li> Item 1 </li>
        <li> Item 2 - Alvo </li>
        <li> Item 3 </li>
    </ul>
</div>

It is worth remembering that the querySelector will only take the first elemento found in the document.

in the example below, only in the first item was applied the CSS:

document.querySelector('span, p').style.color='lightblue';
<span>[span] -  Aqui será aplicado </span> <br>
<span>[span] -  Aqui não será aplicado </span>  

<p>[p] -  Aqui não será aplicado </p>

If multiple elements must be selected, use querySelectorAll that will return an object NodeList, to apply the styles in all, just apply a loop as in the example below:

//selecionando todos os elementos span e p
let obj = document.querySelectorAll('span, p'); 

console.log("tipo: " + typeof obj);
console.log("Quantidade: " +obj.length);

//aplicando o estilo em todos os elementos selecionados
for(let i of obj) {  
    i.style.color= "blue";
}
<span>[span] -  Aqui será aplicado </span> <br>
<span>[span] -  Aqui também será aplicado </span> 
<p>[p] -  Aqui também será aplicado </p>

getElementById

The same is a little more performatic than the querySelector and can be seen in this test here and in that here also.

I believe its use should be done whenever it is necessary to select an element by id, a selection such as the example below, I consider impossible because there is a specific function for identificadores.

Unfeasible example :

document.querySelector("[id=elemento]");

Completion

If you need to select only one element by identificador, it is more viable to use document.getElementById because the same is specific for this purpose, if you need to use a more precise/advanced selection, use document.querySelector for having the freedom to use selectors CSS, which is a great advantage.

Nothing stops you from using querySelector to select an item by id, moreover, it is difficult for an application to suffer from low performance because of this.

  • Good answer. I’ll wait to see if any more appears with more information, otherwise mark yours as accepted.

  • I still intend to perform some adjustments.

  • I guess now it’s okay.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.