I have this javascript code:
var elt = document.createElement("div");
elt.class = "class_1";
There is supposed to be a styling associated with .class_1 in my CSS, but it did not really apply for some reason. After spent a few hours figuring out what went wrong, I tried this alternative:
elt.setAttribute("class", "class_1");
and it worked….
It is weird since on the other part of my code, I used elt.id and it worked just fine. At first I thought it was a cross-browser issue, but it turned out that "elt.class" doesnt work in all browser.
Is this a bug in the native javascript DOM? can somebody explain why this is or if I did anything wrong? Thanks. All inputs/answers would be appreciated.
Properties and attributes are different things. Attributes are the strings you see in the document code, accessible for any type of document through the DOM Core method
getAttribute:whereas the properties, accessible directly on the object, are specialised and document-type-specific (eg defined in DOM HTML or HTML5) and are generally more readable convenience facilities. Although they often reflect the same thing as the attribute, they can differ in terms of name, value, type or purpose.
So whilst
idresults in the same value,hrefand all other URL properties get absolutised relative to the document;tabIndexand other numeric properties returns a Number instead of literal string;onclickand other event handler properties return a JS Function object, and properties whose name happens to clash with common reserved words likeclass(not just only JavaScript reserved words, as DOM is a cross-language standard) get renamed (see also:htmlFor), and non-standard attributes aren’t accessible as properties at all. Other gotchas:value/selected/checkedon inputs reflect the current contents of a form field; the attributes of the same name are thedefaultValue/defaultSelected/defaultCheckedinitial values.[Aside: IE<8 has real trouble telling the difference between attributes and properties, and will return the wrong thing for
getAttributein all cases where they differ. Don’t let this confuse you, and avoid usinggetAttributefor accessing HTML DOM properties for this reason.]