issue is whether to use property or attribute.
have not found this documented, so have run some tests (chromium 12):
property <=> attribute
accept, alt, formMethod, formTarget, id, name, placeholder, type, maxlength, size
form: method, name, target, action, enctype
- can set either property or attribute
- will reflect to property or attribute
- exception 1: if form property will first look for element of that name (!)
- exception 2: action property rewrites itself using value, passes set value to attribute
- exception 3: enctype maintains its integrity, but passes set value to attribute
property <= attribute
value, autofocus, checked, disabled, formNoValidate, multiple, required
- setting property has no effect on attribute
- setting attribute also sets property
property => attribute
indeterminate
- setting property also sets attribute
- setting attribute has no effect on property
propetry >< attribute
defaultValue, validity, defaultChecked, readOnly
form: novalidate
- setting property or attribute has no effect on the other
to me this seems pretty random behavior.
given a random attribute/value to apply to an element, here are the best rules I have come up with (modified as per Tim Down (thanks!) below):
if class, write with classList
, read with className
property
if a form, always read using attribute (and be a little careful)
if typeof element[propName] != "undefined"
, use property, ie, element[attr]=val
otherwise, use attribute, ie, element.setAttribute(attr,val)
is this even close to being right?
note: interestingly, if you have a form with an element named "novalidate", is it even possible to access the novalidate
property of the form itself?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…