Javascript DOM: Setting custom DOM element properties

前端 未结 4 546
北荒
北荒 2020-12-05 18:35

Is it ok to set custom properties on DOM elements, and rely on them persisting?

For example, given

 
&l
相关标签:
4条回答
  • 2020-12-05 18:47

    This is what the specs say about the internal property accessors:

    Host objects may implement these internal methods in any manner unless specified otherwise; for example, one possibility is that [[Get]] and [[Put]] for a particular host object indeed fetch and store property values but [[HasProperty]] always generates false.

    and

    Host objects may define additional constraints upon [[Put]] operations. If possible, host objects should not allow [[Put]] operations in situations where this definition of [[CanPut]] returns false.

    However, I think this is just theoretical, and in reality expandos work as expected.

    0 讨论(0)
  • 2020-12-05 18:50

    No.

    Let's say 5 years ago you thought the property .contains was a good use-case for saying whether an element contained some special data.

    So you wrote document.getElementById("someId").contains = true

    Then you had checks like if (document.getElementByID("someId").contains)

    Today that breaks because Node.prototype.contains is a method.

    basically your code is not future safe.

    0 讨论(0)
  • 2020-12-05 18:56

    As a general rule, don't use custom properties. You shouldn't modify DOM objects in ways they don't expect because they may not behave the way you think they will.

    The mechanism for custom attributes in HTML5 is to use the data- prefix.

    However, HTML5 is not a stanard and is not that widely implemented yet. But if you use set/getAttribute for data- attributes it should work on all reasonably modern browsers and no standard attribute should be introduced in the future with a data- prefix.

    But having said that, I would still recommend using a custom object to store the values and referencing them by element id or class or some other standard (as in HTML 4.01) attribute value. It avoids the issue of custom properties and attributes and is known to work everywhere.

    0 讨论(0)
  • 2020-12-05 18:57

    Well, there is the dataset property:

    div.dataset.bar = 'baz';
    

    but it's not implemented in IE.

    Live demo: http://jsfiddle.net/simevidas/dJr2u/

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