DekGenius.com
Team LiB   Previous Section   Next Section
Element.setAttribute( ) create or change an attribute of an element

Availability

DOM Level 1 Core

Synopsis

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

Element.getAttribute( ), Element.removeAttribute( ), Element.setAttributeNode( )

    Team LiB   Previous Section   Next Section