When to use querySelector instead of getElementById?

0

I searched for some information on the internet about it already, including SOen, though I still have not been able to come to an exact conclusion.

I should point out that the issue is not just 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 getElementById is approximately 5x faster, but I believe there are situations where using querySelector would be better. Legibility maybe?

If getElementById is faster, in what situations does querySelector prove to be a better option?

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

    
asked by anonymous 26.10.2018 / 16:45

2 answers

5

In addition to the performance involved ( getElementById is a little more performative, I will cite some tests below) we can consider:

QuerySelector

The advantage of using it, unlike document.getElementById , document.querySelector can return classes, in addition, it is possible to use seletores CSS , which can not be done with getElementById . p>

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>

Note that querySelector will only get the first elemento found in the document.

In the example below, only the item was applied to the first 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 you need to select multiple elements, use querySelectorAll that will return a NodeList object, to apply the styles to 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 performative than querySelector and can be seen in this test here and in that here also.

I believe that its use should be done whenever it is necessary to select an element by id , a selection like the example below, I consider not feasible because there is a specific function for searches by identificadores .

Unfeasible example:

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

Conclusion

If you need to select only one element with identificador , it is more feasible to use document.getElementById because it is specific for that purpose, if you need to use a more precise / advanced selection, use document.querySelector because you have the freedom of using selectors CSS , which is a great advantage.

Nothing prevents you from using querySelector to select an element by id , moreover, hardly an application will suffer from low performance because of that.

    
26.10.2018 / 17:16
-3

Well, I do not know the complete answer to your question, but one difference between the two is that querySelector/querySelectorAll can be used on nodes of type HTMLElement.

var foo = document.querySelectorAll('.foo')
var bar = document.getElementById('bar')
var barFoo = bar.querySelectorAll('.foo')


console.log('.foo: ', foo.length)
console.log('.foo em #bar:', barFoo.length)
<div id="bar">
  <div class="foo">Foo</div>
</div>

<div class="foo">Foo</div>
<div class="foo">Foo</div>
    
26.10.2018 / 17:01