Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

206
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda