JavaScript: setAttribute

The setAttribute() method adds an attribute to an HTML element or changes the value of an existing attribute.

What you will learn

Syntax

element.setAttribute('attribute-name', 'value');

Minimal example

const link = document.querySelector('#help');
if (link) {
  link.setAttribute('href', '/help.html');
  link.setAttribute('aria-label', 'Open help');
}

If the attribute already exists, its value is replaced. If it does not exist, it is added.

Boolean attributes

const button = document.querySelector('#save');
if (button) button.setAttribute('disabled', '');

For boolean attributes, presence matters. To enable the button again, use removeAttribute('disabled').

Common mistakes