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
property <= attribute
value, autofocus, checked, disabled, formNoValidate, multiple, required
property => attribute
propetry >< attribute
defaultValue, validity, defaultChecked, readOnly form: novalidate
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
if a form, always read using attribute (and be a little careful)
typeof element[propName] != "undefined", use property, ie,
otherwise, use attribute, ie,
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?
Except for rare special cases listed below, always use the property. Once the browser has parsed the intial HTML, attributes are no help to you unless you're serializing the DOM back to HTML for some reason.
Reasons to always favour properties:
checked: just use
falseand never worry whether you should be removing the attribute, or setting it to
checkedproperty of a checkbox or radio button does not correspond to any attribute; the
checkedattribute corresponds to the
defaultCheckedproperty and does not change when the user interacts with the element (except in old IE; see next point). Likewise
getAttribute()are broken in older versions of IE.
<form>elements. Since each form input is mapped to a property of its parent
<form>element corresponding to its
name, it's safer to use
getAttribute()to obtain properties of the form such as
<p myspecialinfo="cabbage">. These will not generally create equivalent properties on the DOM element object, so
getAttribute()should be used.
One final consideration is that there is not an exact correspondence between attribute and property names. For example, the property equivalent of the
class attribute is
className, and the property for the
for attribute is
©2020 All rights reserved.