It appears that sometimes object.setAttribute(attrib,value) isn’t equivalent to object.attrib=value in javascript?
I’ve got the following code, which works fine:
var lastMonthBn = document.createElement('input');
lastMonthBn.value='<'; // This works fine
lastMonthBn.type='button'; // This works fine
But the following code doesn’t:
var div = document.createElement('div');
div.class = 'datepickerdropdown'; // No luck here!
So i need to use the following:
div.setAttribute('class','datepickerdropdown');
My question is, why? From reading this, I thought that object.setAttribute(blah,value) was the same as object.blah=value??
Properties and Attributes aren’t really the same, however the DOM exposes standard attributes through properties.
The problem you’re facing specifically with the
classattribute is thatclassis a future reserved word.In some implementations the use of a future reserved word can cause a
SyntaxErrorexception.For that reason, the HTMLElement DOM interface provides a way to access the
classattribute, through theclassNameproperty:Remember, attributes aren’t the same as properties, for example:
Immagine a DOM element that looks like this:
If you add a custom attribute to it, e.g.:
An attribute will be added to the element:
Accessing
attras a property on the div element, will simply give youundefined(since is not a property).If you bind a property to an element, e.g.:
The
getAttributemethod will not be able to find it, (since is not an attribute):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:
classattribute, is accessible through theclassNameproperty (the problem you have).forattribute ofLABELelements, is accessible through thehtmlForproperty (collides with theforstatement).Attributes are case-insensitive, but the language bindings for JavaScript properties are not, so the convention is to use the names is
camelCaseto access attributes through properties, for example the ones formed by two words, e.g.cellSpacing,colSpan,rowSpan,tabIndex,maxLength,readOnlyframeBorder,useMap.