What is the difference between Document.querySelector and getelementsbytagname?

Asked

Viewed 2,517 times

0

I would like to know the differences in the use of these two commands, because for min that I am at the beginning of the study very similar and even equal in some moments, but having different nomenclatures must have differences between the two.

1 answer

4

I’ll explain one by one and then the difference between them.

document.querySelector(): Returns only the first element with the properties CSS inserted 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 who selects all elements contained in the object being used as a constructor. That is, it 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 through the html tags.

If you want to use the document.querySelector() and return a collection, there is the command document.querySelectorAll() which receives the same parameter but returns collections.

Sources:

https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

  • Thank you very much for the explanation Leonardo!

  • @Brunosuarez helped himself, do not forget to mark as the correct answer !

Browser other questions tagged

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