W3docs

Atributo id de HTML

El atributo id define un identificador único para un elemento HTML, usado para aplicar estilos, enlaces de anclaje y scripts.

El atributo id de HTML asigna un identificador único a un elemento. Ese nombre singular dentro de la página te permite apuntar al elemento desde CSS, enlazar directamente a él desde una URL, obtenerlo con JavaScript y conectarlo para accesibilidad. Como el id es un atributo global, puedes colocarlo en cualquier elemento HTML.

Esta página cubre la única regla que nunca debes romper (la unicidad), la sintaxis válida del id y las cuatro funciones que un id cumple en páginas reales: enlaces de fragmento, estilos CSS, selección con JavaScript y asociaciones de formularios y accesibilidad. El id forma parte de los atributos globales que acepta todo elemento.

La regla fundamental: un id debe ser único

Un valor de id debe ser único dentro de todo el documento — dos elementos no pueden compartir el mismo id. Esta es la diferencia clave con el atributo class, donde un mismo nombre de clase puede reutilizarse en muchos elementos:

  • id — un valor, un elemento. Úsalo para la única cosa de la página (una sección específica, un campo de formulario concreto, el encabezado principal).
  • class — reutilizable, muchos elementos. Úsala para un grupo que debe tener el mismo aspecto o comportamiento.

Si duplicas un id, la página sigue renderizándose, pero las herramientas fallan de formas sutiles: getElementById devuelve solo la primera coincidencia, un enlace #fragmento salta a la primera coincidencia y las reglas CSS con #id se aplican de manera impredecible. Los validadores marcan los ids duplicados como errores.

Sintaxis válida de id

Algunas reglas garantizan que un id funcione en todas partes:

  • Debe tener al menos un carácter.
  • No debe contener espacios en blanco (espacios, tabulaciones, saltos de línea).
  • Es sensible a mayúsculas y minúsculasmain y Main son dos ids diferentes.
  • Para máxima compatibilidad, comienza el valor con una letra (az, AZ) y usa solo letras, dígitos, guiones (-) y guiones bajos (_). Los ids que empiezan con un dígito funcionan en HTML5 pero requieren escape en CSS, por lo que comenzar con una letra es la opción segura.
<!-- Good -->
<div id="main-content"></div>
<section id="pricing"></section>

<!-- Avoid -->
<div id="main content"></div>   <!-- space is invalid -->
<div id="2col"></div>           <!-- digit-first: awkward in CSS -->

Sintaxis

<tag id="id">...</tag>

Ejemplo del atributo id de HTML

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      #grey {
        color: grey;
      }
      #purple {
        color: purple;
      }
    </style>
  </head>
  <body>
    <h1>Example of the HTML id attribute</h1>
    <p id="grey">
      It is a grey paragraph.
    </p>
    <p>This is some text.</p>
    <p id="purple">
      It is a purple paragraph.
    </p>
  </body>
</html>

En el ejemplo anterior, CSS apunta a cada párrafo con el selector #id — un hash (#) seguido del valor del id. Dado que cada id pertenece exactamente a un elemento, solo ese párrafo recibe el estilo.

id y class juntos

id y class suelen aparecer en el mismo elemento. Un patrón común es usar class para los estilos compartidos y un id para el único elemento al que también necesitas enlazar o manipular con scripts. En el siguiente ejemplo, el encabezado lleva un id único mientras varios párrafos comparten una clase reutilizable:

Ejemplo de los atributos id y class de HTML

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      #green-bg {
        background-color: green;
        color: white;
        padding: 20px;
        text-align: center;
      }
      .text-grey {
        color: grey;
        padding: 5px 15px;
      }
    </style>
  </head>
  <body>
    <h1>Example of the HTML "id" and "class" attributes:</h1>
    <p>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
    <h2 id="green-bg">HTML ID attribute</h2>
    <p class="text-grey">
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs.
    </p>
    <p class="text-grey">
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book
    </p>
    <p class="text-grey">
      The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
  </body>
</html>

Enlazar a un id (enlaces de fragmento y marcadores)

Un enlace cuyo href empieza con # es un enlace de fragmento (también llamado ancla o marcador). Apunta al elemento de la misma página cuyo id coincide con el texto que sigue al #. Al hacer clic, la página se desplaza hasta ese elemento — útil para páginas largas, tablas de contenido y enlaces "volver al inicio".

<a href="#pricing">Jump to pricing</a>
...
<section id="pricing">...</section>

También puedes enlazar a un fragmento en otra página combinando una URL con el hash: <a href="/learn-html/global-attributes#id">…</a>. Abrir una página con un fragmento en la barra de direcciones desplaza directamente al elemento correspondiente.

Ejemplo de cómo agregar un marcador

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p {
        line-height: 1.5;
        color: #777777;
      }
      a {
        color: #20c7c1;
        display: inline-block;
        padding: 5px 15px;
      }
      strong {
        display: block;
        color: #1129dc;
      }
    </style>
  </head>
  <body>
    <h1>Example of the HTML "id" and "class" attributes:</h1>
    <p>Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.</p>
    <a href="#text2">Jump to the text-2</a>
    <a href="#text3">Jump to the text-3</a>
    <p id="text-1">
      <strong>Text number 1</strong> Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs.
    </p>
    <p id="text2">
      <strong>Text number 2</strong> Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book. Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book
    </p>
    <p id="text3">
      <strong>Text number 3</strong> Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
    <p>
      <strong>Text number 4</strong> Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
    <p>
      <strong>Text number 5</strong> Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
  </body>
</html>

Seleccionar un id con JavaScript

Como cada id es único, es la forma más directa de acceder a un elemento desde un script. Dos enfoques habituales:

<button id="save-btn">Save</button>

<script>
  // Fastest, dedicated method for ids:
  const btn = document.getElementById("save-btn");

  // querySelector uses the CSS #id selector (note the hash):
  const sameBtn = document.querySelector("#save-btn");

  btn.addEventListener("click", () => {
    console.log("Saved!");
  });
</script>

getElementById recibe el valor del id sin el #, mientras que querySelector usa el selector CSS #id completo. Ambos devuelven solo el primer elemento coincidente, lo que es una razón más para mantener los ids únicos.

Formularios y accesibilidad

Los ids son la forma en que los elementos se referencian entre sí, lo que los hace fundamentales para los formularios accesibles y el soporte de lectores de pantalla:

  • <label for="…"> conecta una etiqueta a un control de formulario cuyo id coincide. Al hacer clic en la etiqueta, el foco se mueve al campo, y las tecnologías de asistencia anuncian la etiqueta cuando el campo recibe el foco.
  • aria-labelledby="…" nombra un elemento usando el texto de otro elemento referenciado por su id.
  • aria-describedby="…" apunta a un elemento (por id) que proporciona ayuda adicional o texto de error.
  • Skip links — un enlace "Saltar al contenido" (href="#main") apunta al id de la región principal para que los usuarios de teclado puedan omitir la navegación.
<label for="email">Email address</label>
<input type="email" id="email" aria-describedby="email-help">
<p id="email-help">We'll never share your email.</p>

Aquí tanto for como aria-describedby hacen referencia a ids, de modo que el navegador sabe que la etiqueta, el campo y el texto de ayuda pertenecen juntos.

Una nota sobre la especificidad en CSS

El selector CSS #id es muy específico — mucho más fuerte que un selector de clase o de elemento. Ese poder es también una trampa: las reglas escritas con ids son difíciles de sobrescribir y generan "guerras de especificidad" en las que se acumulan más selectores (o !important) para imponerse. Para los estilos reutilizables, prefiere las clases; reserva los selectores #id para casos genuinamente únicos. Para un análisis más profundo sobre cómo elegir entre ellos en hojas de estilo, consulta CSS id and class.

Práctica

Práctica
¿Cuál afirmación sobre el atributo 'id' de HTML es correcta?
¿Cuál afirmación sobre el atributo 'id' de HTML es correcta?
Was this page helpful?