javascript - difference between setAttribute and htmlElement.attribute='value' -


what difference between 2 ,

b1.setattribute('id','b1'); 

and

b1.id='b1'; 

is 1 of them more efficient other ? , both of them same task ? , different in situations ?

difference between setattribute , htmlelement.attribute='value'

that latter bit, htmlelement.attribute='value', isn't quite accurate. you're not setting attribute there, you're setting property.

dom element instances in memory have various properties, some of connect or relate attributes , others don't.

attributes, on other hand, name/value pairs read directy html markup (and if serialize dom element, instance accessing innerhtml property, written markup back).

when property , attribute related/linked in way, property called reflected property (of attribute). sometimes, reflected property's name isn't quite same attribute's name (class becomes classname, for becomes htmlfor), , link between them isn't 1:1.

so instance, id reflected property of id attribute. select boxes have selectedindex property there's no attribute.

do both of them same task ?

and different in situations ?

it depends on attribute/property:

  • id , several others directly reflected: setting id property , setting id attribute same thing. offhand, true of htmlfor property / for attribute (except on old ie has bugs in setattribute there), rel property/attribute, classname / class attribute (except on old ie has bugs in setattribute there), name attribute on form fields , other elements, method , action properties/attributes on forms, , several others.

  • the value property, on other hand, doesn't set value attribute at all. gets default value it. on browsers ("all" @ point?), there's separate defaultvalue property does directly reflect value attribute.

  • the href property different href attribute in relation relative vs. absolute links. attribute can contain relative path, , using str = elm.getattribute("href") gives relative path; if read property (str = elm.href), absolute path (e.g., resolved path). setting href property relative path sets attribute path, again reading teh href property give absolute (resolved) version. setting href property absolute path set attribute absolute path.

  • there several boolean properties represented booleans (true/false), since attribute values strings, attribute either not there false (getattribute returns null) or there true. if it's there, must have value "" or same name (e.g., multiple="multiple", case-insensitive), although in practice browsers treat present attribute true regardless of actual content.

  • several properties aren't reflected in attributes @ all, setting them doesn't set/change attribute.

is 1 of them more efficient other ?

it's never going make big enough difference care, doesn't matter. varies dramatically browser.


Comments