javascript dom, how to handle “special properties” as versus attributes?

后端 未结 1 515
余生分开走
余生分开走 2020-12-09 12:19

issue is whether to use property or attribute.

have not found this documented, so have run some tests (chromium 12):

property <=> attribute

相关标签:
1条回答
  • 2020-12-09 12:31

    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:

    • dealing with properties is simpler (see Boolean properties such as checked: just use true and false and never worry whether you should be removing the attribute, or setting it to "" or "checked")
    • not every property maps to an attribute of the same name. For example, the checked property of a checkbox or radio button does not correspond to any attribute; the checked attribute corresponds to the defaultChecked property and does not change when the user interacts with the element (except in old IE; see next point). Likewise value and defaultValue.
    • setAttribute() and getAttribute() are broken in older versions of IE.

    Special cases:

    • Attributes of <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 setAttribute() and getAttribute() to obtain properties of the form such as action, name and method.
    • Custom attributes, e.g. <p myspecialinfo="cabbage">. These will not generally create equivalent properties on the DOM element object, so setAttribute() and 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 htmlFor.

    0 讨论(0)
提交回复
热议问题