dom - Sometimes object.setAttribute(attrib,value) isn't equivalent to object.attrib=value in javascript? -


it appears object.setattribute(attrib,value) isn't equivalent object.attrib=value in javascript?

i've got following code, works fine:

var lastmonthbn = document.createelement('input'); lastmonthbn.value='<';     // works fine lastmonthbn.type='button'; // works fine 

but following code doesn't:

var div = document.createelement('div'); div.class = 'datepickerdropdown'; // no luck here! 

so need use following:

div.setattribute('class','datepickerdropdown'); 

my question is, why? reading this, thought object.setattribute(blah,value) same object.blah=value??

properties , attributes aren't same, dom exposes standard attributes through properties.

the problem you're facing class attribute class future reserved word.

in implementations use of future reserved word can cause syntaxerror exception.

for reason, htmlelement dom interface provides way access class attribute, through classname property:

var div = document.createelement('div'); div.classname = 'datepickerdropdown'; 

remember, attributes aren't same properties, example:

immagine dom element looks this:

<div></div> 

if add custom attribute it, e.g.:

mydiv.setattribute('attr', 'test'); 

an attribute added element:

<div attr="test"></div> 

accessing attr property on div element, give undefined (since not property).

mydiv.foo; // undefined 

if bind property element, e.g.:

mydiv.prop = "test"; 

the getattribute method not able find it, (since not attribute):

mydiv.getattribute('test'); // null 

note: ie wrongly messes attributes , properties. :(

as i've said before, dom exposes standard attributes properties, there exceptions you'll have know:

  • the class attribute, accessible through classname property (the problem have).
  • the for attribute of label elements, accessible through htmlfor property (collides for statement).

attributes case-insensitive, language bindings javascript properties not, convention use names camelcase access attributes through properties, example ones formed 2 words, e.g. cellspacing, colspan, rowspan, tabindex, maxlength, readonly frameborder, usemap.


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -