Properties and Attributes aren't really the same, however the DOM exposes standard attributes through properties.
The problem you're facing specifically with the class
attribute is that class
is a future reserved word.
In some implementations the use of a future reserved word can cause a SyntaxError
exception.
For that reason, the HTMLElement DOM interface provides a way to access the class
attribute, through the className
property:
var div = document.createElement('div');
div.className = 'datepickerdropdown';
Remember, attributes aren't the same as properties, for example:
Immagine a DOM element that looks like this:
<div></div>
If you add a custom attribute to it, e.g.:
myDiv.setAttribute('attr', 'test');
An attribute will be added to the element:
<div attr="test"></div>
Accessing attr
as a property on the div element, will simply give you undefined
(since is not a property).
myDiv.foo; // undefined
If you bind a property to an element, e.g.:
myDiv.prop = "test";
The getAttribute
method will not be able to find it, (since is not an attribute):
myDiv.getAttribute('test'); // null
Note: IE wrongly messes up attributes and properties. :(
As I've said before, the DOM exposes standard attributes as properties, but there are some exceptions that you'll have to know:
- The
class
attribute, is accessible through the className
property (the problem you have).
- The
for
attribute of LABEL
elements, is accessible through the htmlFor
property (collides with the for
statement).
Attributes are case-insensitive, but the language bindings for JavaScript properties are not, so the convention is to use the names is camelCase
to access attributes through properties, for example the ones formed by two words, e.g. cellSpacing
, colSpan
, rowSpan
, tabIndex
, maxLength
, readOnly
frameBorder
, useMap
.