Easy Tutorial
❮ Prop Element Previoussibling Met Element Getelementsbytagnamens ❯

XML DOM setAttribute() Method



Definition and Usage

The setAttribute() method adds a new attribute.

If the element already has an attribute with the specified name, its value is changed to the value of the value parameter.

Syntax

Parameter Description
name Required. Specifies the name of the attribute to set.
value Required. Specifies the value of the attribute to set.

Example

The following code snippet uses [loadXMLDoc()](dom-loadxmldoc.html) to load "books.xml" into xmlDoc and adds an "edition" attribute to all <book> elements:

Example

xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName('title');

// Add a new attribute to each title element
for(i=0;i&lt;x.length;i++)
{
  x[i].setAttribute("edition","first");
}

// Output the title and edition values
for (i=0;i&lt;x.length;i++)
{
  document.write(x[i].childNodes[0].nodeValue);
  document.write(" - Edition: ");
  document.write(x[i].getAttribute('edition'));
  document.write("<br>");
}

Output:

Everyday Italian - Edition: first
Harry Potter - Edition: first
XQuery Kick Start - Edition: first
Learning XML - Edition: first

Try It

setAttribute() - Change Attribute Value


❮ Prop Element Previoussibling Met Element Getelementsbytagnamens ❯