Añadir o cambiar atributos HTML con setAttribute() en JavaScript

element.setAttribute(name, value) añade un atributo HTML o reemplaza su valor. Lee el valor con getAttribute(). Usa hasAttribute() si solo necesitas saber si el atributo existe.

Asignar un atributo y leer su valor

Selecciona un elemento existente y pasa el nombre y el valor. El método devuelve undefined. En elementos HTML de un documento HTML convierte el nombre a minúsculas. Un nombre con espacios puede provocar InvalidCharacterError. Abre primero el ejemplo completo. Consulta setAttribute().

{
  const link = document.querySelector('#sample-link');
  link.setAttribute('title', 'Descripción actualizada');
  link.setAttribute('data-state', 'updated');

  console.log(link.getAttribute('title'));      // 'Descripción actualizada'
  console.log(link.hasAttribute('data-state'));  // true
}

Usar atributos booleanos como disabled

disabled es booleano. Su presencia desactiva el botón incluso con el texto 'false'. Añádelo con una cadena vacía y elimínalo para volver a activar el botón del ejemplo. Consulta los atributos booleanos.

{
  const button = document.querySelector('#target');
  button.setAttribute('disabled', '');
  console.log(button.disabled); // true

  button.removeAttribute('disabled');
  console.log(button.disabled); // false
}

Distinguir cadenas y atributos ausentes

Un atributo normal almacena una cadena. 0 y null se guardan como '0' y 'null'. Ejecuta la comparación en la consola del navegador.

{
  const element = document.createElement('div');
  element.setAttribute('data-count', 0);
  const zero = element.getAttribute('data-count');
  console.log(zero, typeof zero); // 0 string

  element.setAttribute('data-count', null);
  const textNull = element.getAttribute('data-count');
  console.log(textNull, typeof textNull); // null string

  element.removeAttribute('data-count');
  console.log(element.getAttribute('data-count') === null, element.hasAttribute('data-count')); // true false
}

Las primeras líneas muestran 0 string y null string. Al eliminar el atributo, getAttribute() devuelve el valor null y hasAttribute() devuelve false. Un atributo puede existir con un valor vacío.

Probar un ejemplo completo con restablecimiento

Guarda el HTML en UTF-8 como set-attribute-example.html y ábrelo. Cambiar atributos modifica title, añade data-state y desactiva el botón de destino. Restablecer recupera el estado inicial y sigue disponible. Al principio falta data-state y disabled vale false. Tras cambiar, se leen updated y true.

<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Añadir y cambiar atributos</title>
</head>
<body>
<p><a id="sample-link" href="#example" title="Descripción original">Enlace de ejemplo</a></p>
<button id="target" type="button">Botón de destino</button>
<button id="change" type="button">Cambiar atributos</button>
<button id="reset" type="button">Restablecer</button>
<p id="result" aria-live="polite"></p>
<p id="example">El enlace apunta a esta ubicación del mismo documento.</p>
<script>
const link = document.querySelector('#sample-link');
const target = document.querySelector('#target');
const result = document.querySelector('#result');

function show() {
  result.textContent = `title: ${link.getAttribute('title') ?? '(ausente)'}; ` +
    `data-state: ${link.getAttribute('data-state') ?? '(ausente)'}; ` +
    `disabled: ${target.disabled}; ` +
    `Atributo disabled presente: ${target.hasAttribute('disabled')}`;
}

document.querySelector('#change').addEventListener('click', () => {
  link.setAttribute('title', 'Descripción actualizada');
  link.setAttribute('data-state', 'updated');
  target.setAttribute('disabled', '');
  show();
});

document.querySelector('#reset').addEventListener('click', () => {
  link.setAttribute('title', 'Descripción original');
  link.removeAttribute('data-state');
  target.removeAttribute('disabled');
  show();
});
show();
</script>
</body>
</html>

Elegir el método adecuado para los atributos

Espera a que exista el elemento. Usa addEventListener() para eventos y valida las direcciones antes de asignar atributos de navegación. Los atributos y propiedades JavaScript pueden tener significados distintos.