JavaScript: setAttribute
The setAttribute() method adds an attribute to an HTML element or changes the value of an existing attribute.
What you will learn
- How to add or change an attribute
- How to set a boolean attribute such as disabled
- When a property or classList may be clearer
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
- Pass the attribute name without a CSS selector such as
#or.. - Use
classList.add()when adding one class without replacing other classes. - Do not insert untrusted strings into URL or event-handler attributes without validating them.