Name

Element.setAttribute( ): create or change an attribute of an element — DOM Level 1 Core:

Synopsis

void setAttribute(Stringname,
                  String value)
    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 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 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( )

Get JavaScript: The Definitive Guide, 5th 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.