CKTIS / JavaScript
Element.setAttribute — setting an attribute
Element.setAttribute takes a name and a value for an attribute on a DOM element. On success, it adds the attribute or replaces its value.
Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support
Syntax
element.setAttribute(qualifiedName, value)On success, element.setAttribute(qualifiedName, value) creates a missing attribute or updates the first attribute with that name. This is a DOM method, not a function of ECMAScript itself.
When the Content Security Policy (CSP) enforces Trusted Types, passing a plain string as the value for a protected attribute such as onclick can throw a TypeError without creating or updating the attribute.
For elements in the HTML namespace belonging to an HTML document, the name is converted to ASCII lowercase. An invalid name throws an InvalidCharacterError DOMException. Use setAttributeNS to set attributes with a specified namespace.
Examples
const element = document.createElement('div');
element.setAttribute('data-state', 'draft');
element.setAttribute('data-state', 'ready');
console.log(element.getAttribute('data-state'));Result
ready
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version. The `data-state` example does not show how Trusted Types enforcement affects a protected attribute.