Can I add arbitrary properties to JavaScript DOM objects, such as <INPUT>
or <SELECT>
elements? Or, if I cannot do that, is there a way to associate my own objects with page elements via a reference property?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
I was exploring answers and want to add that we can set attributes on
domElements
with usingdataset
property, it could use onHTMLOrForeignElement
(that's a mixin of several features common to theHTMLElement
,SVGElement
andMathMLElement
interfaces).According to mdn
Although there are concerns about Internet Explorer support and performance on this you can check here.
Sure, people have been doing it for ages. It's not recommended as it's messy and you may mess with existing properties.
If you are looping code with
for..in
your code may break because you will now be enumerating through these newly attached properties.I suggest using something like jQuery's
.data
which keeps metadata attached to objects. If you don't want to use a library, re-implementjQuery.data
If you must, don't use standard HTML attributes. Here's a tutorial on using custom attributes:
http://www.javascriptkit.com/dhtmltutors/customattributes.shtml
It's HTML5, but it's backward-compatible.
ECMAScript 6 has WeakMap which lets you associate your private data with a DOM element (or any other object) for as long as that object exists.
Unlike other answers, this method guarantees there will never be a clash with the name of any property or data.
Yes, you can add your own properties to DOM objects, but remember to take care to avoid naming collisions and circular references.
HTML5 introduced a valid way of attaching data to elements via the markup - using the
data-
attribute prefix. You can use this method in HTML 4 documents with no issues too, but they will not validate:Which you can access via JavaScript using
getAttribute()
:Do you want to add properties to the object, or attributes to the element?
You can add attributes using
setAttribute
or you can just add properties to the javascript object: