I would like to know the differences in the use of these two commands, because for min that I am in the beginning of the study very similar and even equal in some moments, but having different nomenclatures one must have differences between the two.
I would like to know the differences in the use of these two commands, because for min that I am in the beginning of the study very similar and even equal in some moments, but having different nomenclatures one must have differences between the two.
I'll explain one by one and then the difference between them.
document.querySelector()
:
Returns only the first element with the CSS
properties entered as a parameter and can only be used in the scope of document
. Example:
console.log("Retorna apenas o primeiro elemento que deu match:")
console.log(document.querySelector("table"))
<table id="table-01">
<tr>
<td></td>
<td></td>
</tr>
</table>
<table id="table-02">
<tr>
<td></td>
<td></td>
</tr>
</table>
Element.getElementsByTagName()
:
It is a function of the class object
that selects all elements contained in the object that is being used as a constructor. That is, returns a collection of objects.
Example:
var table1 = document.getElementById("table-01");
console.log("Retorna TODOS os td's dentro de document")
console.log(document.getElementsByTagName("td"));
console.log("Retorna TODOS os td's dentro do objeto table1")
console.log(table1.getElementsByTagName("td"));
<table id="table-01">
<tr>
<td>casa</td>
<td>prédio</td>
</tr>
</table>
<table id="table-02">
<tr>
<td>rua</td>
<td>avenida</td>
</tr>
</table>
The difference is:
document.querySelector()
returns only one object through a CSS selector .
Element.getElementsByTagName()
returns a collection of objects via html tags.
If you want to use document.querySelector()
and return a collection, the document.querySelectorAll()
that receives the same parameter but returns collections.
Sources: