04.11.2015 Views

javascript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 10: The Document Object Model<br />

The last method is removeAttribute() , which removes the attribute from the element altogether. This<br />

does more than just clear the attribute ’ s value; it completely removes the attribute from the element as<br />

shown here:<br />

div.removeAttribute(“class”);<br />

This method isn ’ t used very frequently, but it can be useful for specifying exactly which attributes to<br />

include when serializing a DOM element.<br />

IE versions 6 and earlier don ’ t support removeAttribute() .<br />

The attributes Property<br />

The Element type is the only DOM node type that uses the attributes property. The attributes<br />

property contains a NamedNodeMap , which is a “ live ” collection similar to a NodeList . Every attribute<br />

on an element is represented by an Attr node, each of which is stored in the NamedNodeMap object. A<br />

NamedNodeMap object has the following methods:<br />

❑<br />

❑<br />

❑<br />

❑<br />

getNamedItem( name ) — Returns the node whose nodeName property is equal to name<br />

removeNamedItem( name ) — Removes the node whose nodeName property is equal to name<br />

from the list<br />

setNamedItem( node ) — Adds the node to the list, indexing it by its nodeName property<br />

item( pos ) — Returns the node in the numerical position pos<br />

Each node in the attributes property is a node whose nodeName is the attribute name and whose<br />

nodeValue is the attribute ’ s value. To retrieve the id attribute of an element, you can use the following code:<br />

var id = element.attributes.getNamedItem(“id”).nodeValue;<br />

Following is a shorthand notation for accessing attributes by name using bracket notation:<br />

var id = element.attributes[“id”].nodeValue;<br />

It ’ s possible to use this notation to set attribute values as well, retrieving the attribute node and then<br />

setting the nodeValue to a new value, as this example shows:<br />

element.attributes[“id”].nodeValue = “someOtherId”;<br />

The removeNamedItem() method functions the same as the removeAttribute() method on the<br />

element — it simply removes the attribute with the given name. The following example shows how the<br />

sole difference is that removeNamedItem() returns the Attr node that represented the attribute:<br />

var oldAttr = element.attributes.removeNamedItem(“id”);<br />

The setNamedItem() is a rarely used method that allows you to add a new attribute to the element by<br />

passing in an attribute node as shown in this example:<br />

element.attributes.setNamedItem(newAttr);<br />

285

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!