Example 1 — Read Explicit role
Unset elements return null; an attribute returns its string.
const plain = document.createElement("div");
const withRole = document.createElement("div");
withRole.setAttribute("role", "button");
console.log(plain.role); // null
console.log(withRole.role); // "button" How It Works
- Create two divs. Neither has special HTML semantics like
<button>. - Leave one unset.
roleisnull(no explicit attribute). - Set
role="button"on the other via the attribute. - Read
.role. You get the explicit string"button".

