XML DOM setAttribute()Methods


Element object

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

elementNode.setAttribute(name,value)

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


Example

The following code snippet usesloadXMLDoc()put "books.xml" Load into xmlDoc, and add 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<x.length;i++) { x[i].setAttribute("edition","first"); } //Output title and edition values for (i=0;i<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 Yourself »

Try it Yourself

setAttribute() - Change the value of an attribute


Element objectother extensions