Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

209
Visualizações
Which DOM selector to use in selecting HTML elements

There are various DOM selector like querySelector , querySelectorAll, getElementById, getELementsByClassName and many more. But my question is when and where we should use which selector during programming. Are there any best practices that tells to specifically use the selector for this task.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

querySelector returns one (the first) element found, and uses a CSS style selector.

querySelectorAll returns a node list (which, depending on your browser support, you may need to convert to an array to work with), and uses the same CSS style selector.

getElementById takes a string and only finds an element that matches that ID (IDs should be unique).

getElementsByClassName takes a string and matches like ID, but can return an array like list of elements.

If you're familiar with CSS selectors, you can use querySelector and querySelectorAll for almost every situation. The performance is pretty close to the getElement* ones, but they're much more powerful. For example, if you wanted to get a span that is the first child of a class in an id, you could do .querySelector('#id .class span') instead of chaining together .getElementById('id').getElementsByClass('class')[0].getElementsByTagName('span')[0].

about 4 years ago · Juan Pablo Isaza Relatório

0

I don't think there's any specific rules on what to use when but I'll share my opinions regarding each method:

  • getElementById: Can be used for elements that only exist once and have an id
  • getElementsByClassName: For elements that have a class name that can be queried
  • querySelector: Use it when you want to query one specific element
  • querySelectorAll: same as querySelector but for multiple elements

caniuse.com is a great resource to check browser support.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda