Name
Element.setAttribute( ): create or change an attribute of an element — DOM Level 1 Core:
Synopsis
void setAttribute(Stringname, Stringvalue) throws DOMException;
Arguments
-
name The name of the attribute to be created or modified.
-
value The string value of the attribute.
Throws
This method may throw a DOMException with the following
code values:
-
INVALID_CHARACTER_ERR The
nameargument contains a character that is not allowed in HTML or XML attribute names.-
NO_MODIFICATION_ALLOWED_ERR This element is read-only and does not allow modifications to its attributes.
Description
This method sets the specified attribute to the specified value. If no attribute by that name already exists, a new one is created.
Note that HTMLElement objects of an HTML document define JavaScript properties that correspond to all standard HTML attributes. Thus, you need to use this method only if you want to set a nonstandard attribute.
Example
// Set the TARGET attribute of all links in a document
var links = document.body.getElementsByTagName("a");
for(var i = 0; i < links.length; i++) {
links[i].setAttribute("target", "newwindow");
// Or more easily: links[i].target = "newwindow"
}See Also
Element.getAttribute( ),
Element.removeAttribute( ),
Element.setAttributeNode(
)
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access