Can I add arbitrary properties to DOM objects?

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?


Solution 1:

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.

const wm = new WeakMap();
el = document.getElementById("myelement");
wm.set(el, "my value");
console.log(wm.get(el)); // "my value"

Unlike other answers, this method guarantees there will never be a clash with the name of any property or data.

Solution 2:

Yes, you can add your own properties to DOM objects, but remember to take care to avoid naming collisions and circular references.

document.getElementById("myElement").myProperty = "my value";

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:

<div id="myElement" data-myproperty="my value"></div>

Which you can access via JavaScript using getAttribute():

document.getElementById("myElement").getAttribute("data-myproperty");

Solution 3:

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-implement jQuery.data

Solution 4:

Do you want to add properties to the object, or attributes to the element?

You can add attributes using setAttribute

var el = document.getElementById('myelement');
el.setAttribute('custom', 'value');

or you can just add properties to the javascript object:

var el = document.getElementById('myelement');
el.myProperty = 'myValue';