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.