Name
Element.setAttribute( ) — create or change an attribute of an element
Availability
DOM Level 1 Core
Synopsis
void setAttribute(Stringname
, Stringvalue
) throws DOMException;
Arguments
-
name
The name of the attribute that is 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
name
argument 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 Element objects that represent the tags of an HTML document also implement the HTMLElement interface and (usually) one of its tag-specific subinterfaces. As a shortcut, these interfaces define properties that correspond to the standard HTML attributes for each tag, and it is usually easier to set an HTML attribute simply by setting the appropriate property.
The value
argument is a plain string. If
you are working with an XML document and need to include an entity
reference in an attribute value, use setAttributeNode( )
.
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"); }
See Also
Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.