Métodos de selección del DOM en JavaScript

Guía clara de los métodos de selección del DOM en JavaScript, con ejemplos y buenas prácticas. Aprende a usar querySelector, getElementById y más para crear apps seguras y eficientes.

1 sept 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Comprender los métodos de selección del DOM en JavaScript es clave para manipular la interfaz, optimizar el rendimiento y construir aplicaciones a medida robustas. A continuación encontrarás una guía clara y práctica de las formas más comunes de seleccionar elementos en el DOM, con ejemplos comentados y consejos de uso. En Q2BSTUDIO desarrollamos software a medida y aplicaciones a medida con estándares de calidad empresarial, integrando buenas prácticas de frontend, backend e inteligencia artificial para lograr productos eficientes y seguros. Si buscas un partner técnico, descubre cómo abordamos proyectos end to end en desarrollo de aplicaciones y software multiplataforma.

1. document.querySelector()

Devuelve el primer elemento que coincide con un selector CSS. Siempre retorna un único elemento o null.

HTML de ejemplo

<p class="text">Hola</p>
<p class="text">Mundo</p>

JS

let resultado = document.querySelector(".text");
console.log(resultado.textContent); // Salida Hola primer elemento

Úsalo cuando solo necesites el primer elemento que coincida con el selector.

2. document.querySelectorAll()

Devuelve todos los elementos que coinciden con un selector CSS. Retorna un NodeList estático sobre el que puedes iterar.

HTML de ejemplo

<p class="text">Hola</p>
<p class="text">Mundo</p>

JS

let todos = document.querySelectorAll(".text");
todos.forEach(p => console.log(p.textContent));
// Salida
// Hola
// Mundo

Úsalo cuando necesites todas las coincidencias.

3. document.getElementById()

Selecciona un elemento por su id único. Siempre retorna un solo elemento o null.

HTML de ejemplo

<p id="titulo">Bienvenido de nuevo</p>

JS

let cabecera = document.getElementById("titulo");
console.log(cabecera.textContent); // Salida Bienvenido de nuevo

4. document.getElementsByClassName()

Devuelve todos los elementos con una clase dada. Retorna un HTMLCollection en vivo que se actualiza si el DOM cambia.

HTML de ejemplo

<p class="nota">Primera</p>
<p class="nota">Segunda</p>

JS

let notas = document.getElementsByClassName("nota");
console.log(notas[0].textContent); // Salida Primera
console.log(notas[1].textContent); // Salida Segunda

Ideal para manejar múltiples elementos que comparten la misma clase.

5. document.getElementsByTagName()

Devuelve todos los elementos por nombre de etiqueta. Retorna un HTMLCollection en vivo.

HTML de ejemplo

<h1>Encabezado 1</h1>
<h1>Encabezado 2</h1>

JS

let h1s = document.getElementsByTagName("h1");
console.log(h1s.length); // Salida 2

Útil para seleccionar por tipo de etiqueta como div, p, h1, etc.

6. document.getElementsByName()

Devuelve todos los elementos con un atributo name. Muy usado en formularios.

HTML de ejemplo

<input type="radio" name="genero" value="masculino"> Masculino
<input type="radio" name="genero" value="femenino"> Femenino

JS

let generos = document.getElementsByName("genero");
generos.forEach(input => console.log(input.value));
// Salida
// masculino
// femenino

Resumen rápido

getElementById Devuelve un solo elemento Basado en id Tipo Element o null Notas el id debe ser único

getElementsByClassName Devuelve múltiples elementos Basado en class Tipo HTMLCollection en vivo Notas se actualiza si el DOM cambia

getElementsByTagName Devuelve múltiples elementos Basado en tag Tipo HTMLCollection en vivo Notas ejemplos p div h1

getElementsByName Devuelve múltiples elementos Basado en atributo name Tipo NodeList Notas muy usado en formularios

querySelector Devuelve el primer elemento coincidente Basado en selector CSS Tipo Element o null Notas muy flexible

querySelectorAll Devuelve todas las coincidencias Basado en selector CSS Tipo NodeList estático Notas no se actualiza automáticamente

Buenas prácticas

- Usa getElementById cuando tengas un id único es el más rápido y claro. - Prefiere querySelector y querySelectorAll por su flexibilidad con selectores complejos. - Recuerda que HTMLCollection es en vivo y NodeList puede ser estático esto afecta cómo responden a cambios dinámicos del DOM. - Convierte colecciones a arrays si necesitas métodos de array Array.from o spread.

En Q2BSTUDIO combinamos estas prácticas de frontend con arquitectura escalable y seguridad desde el diseño para entregar software a medida confiable. Nuestro equipo integra inteligencia artificial, agentes IA e ia para empresas en productos de nueva generación, y reforzamos ciberseguridad con auditorías y pentesting. Además, desplegamos soluciones en servicios cloud aws y azure y habilitamos analítica con servicios inteligencia de negocio y power bi. Si necesitas un partner para crear aplicaciones a medida listas para crecer, conoce nuestro enfoque en software a medida y aplicaciones a medida.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat