Content attributes and DOM properties
In earlier versions of Windows Internet Explorer, content attributes were represented on JavaScript objects as Document Object Model (DOM)] expandos. Starting with Windows Internet Explorer 9, content attributes are no longer connected to DOM expandos; this improves interoperability between Internet Explorer and other browsers.
A content attribute is an attribute that is specified in the HTML source, for example, <element attribute1="value" attribute2="value">
. Many content attributes are predefined as part of HTML; HTML also supports additional user-defined content attributes.
DOM expandos are the values that can be retrieved from an object in JavaScript, for example, document.all["myelement"].domExpando
. Most objects have a predefined set of properties that typically represent the value of their same-named content attribute. JavaScript supports additional user-defined properties as well.
In the following example, id and class are predefined content attributes in HTML and myAttr is a user-defined content attribute:
<div id="myElement" class="b" myAttr="custom"></div>
In the following script sample, id and className are predefined properties:
var div = document.getElementById("myElement");
var divId = div.id; // Gets the value of the id content attribute
var divClass = div.className; // Gets the value of the class content attribute
In Windows Internet Explorer 8 and before (including IE8 Standards mode and previous modes in Internet Explorer 9), the presence of the myAttr content attribute would imply the presence of a myAttr DOM expando:
var divExpando = div.myAttr; // divExpando would get the value "custom" in IE8
The breaking change in Internet Explorer 9 is that DOM expandos will no longer be implied by the presence of user-defined content attributes:
var divExpando = div.myAttr; // divExpando would get an undefined value
Retrieving a user-defined value from a DOM expando works as intended in IE8 mode but an undefined variable is returned in IE9 Standards mode.
This problem can manifest as a script error, but rarely will the problem be seen directly at the point of failure in the JavaScript program. Rather the failure will typically be seen later when the value (presumably) retrieved from the DOM expando is used in another part of the code.
To fix this issue, use the 'getAttribute' API to retrieve the value of user-defined content attributes. This workaround is recommended for all versions of IE and does not require special-casing for new versions compared to older versions of IE.
Instead of using this code:
var divExpando = div.myAttr;
Use this code:
var divExpando = div.getAttribute("myAttr");