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 />

In IE versions 7 and earlier, the getAttribute() method for the<br />

style attribute and event handling attributes such as onclick always return the same<br />

value as if they were accessed via a property. So, getAttribute( “ style ” ) returns an<br />

object and getAttribute( “ onclick ” ) returns a function. Though fixed in IE 8.0, this<br />

inconsistency is another reason to avoid using getAttribute() for HTML attributes.<br />

Setting Attributes<br />

The sibling method to getAttribute() is setAttribute() , which accepts two arguments: the name<br />

of the attribute to set and the value to set it to. If the attribute already exists, setAttribute() replaces<br />

its value with the one specified; if the attribute doesn ’ t exist, setAttribute() creates it and sets its<br />

value. Here is an example:<br />

div.setAttribute(“id”, “someOtherId”);<br />

div.setAttribute(“class”, “ft”);<br />

div.setAttribute(“title”, “Some other text”);<br />

div.setAttribute(“lang”,”fr”);<br />

div.setAttribute(“dir”, “rtl”);<br />

The setAttribute() method works with both HTML attributes and custom attributes in the same way.<br />

Attribute names get normalized to lowercase when set using this method, so “ ID ” ends up as “ id ” .<br />

Because all attributes are properties, assigning directly to the property can set the attribute values, as<br />

shown here:<br />

div.id = “someOtherId”;<br />

div.align = “left”;<br />

Note that adding a custom property to a DOM element, as the following example shows, does not<br />

automatically make it an attribute of the element:<br />

div.mycolor = “red”;<br />

alert(div.getAttribute(“mycolor”));<br />

//null (except in IE)<br />

This example adds a custom property named mycolor and sets its value to “ red ” . In most browsers,<br />

this property does not automatically become an attribute on the element, so calling getAttribute() to<br />

retrieve an attribute with the same name returns null . In IE, however, custom properties are considered<br />

to be attributes of the element and vice versa.<br />

IE versions 7 and earlier had some abnormal behavior regarding setAttribute() .<br />

Attempting to set the class or style attributes has no effect, similar to setting an<br />

event-handler property using setAttribute() . Even though these issues were<br />

resolved in IE 8.0, it ’ s always best to set these attributes using properties.<br />

284

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

Saved successfully!

Ooh no, something went wrong!