Can I add arbitrary properties to DOM objects?

JavascriptDom

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

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';

Solution 5 - Javascript

In case someone is wondering in 2015, yes, you can - and jQuery is doing just that in data. Just pick future-proof names like vendor prefixes or time-based random suffixes (jQuery).

Solution 6 - Javascript

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.

Solution 7 - Javascript

I was exploring answers, none have mentioned that in modern JavaScript we can set attributes on domElements using dataset property, it could use on HTMLOrForeignElement (that's a mixin of several features common to the HTMLElement, SVGElement and MathMLElement interfaces).

According to MDN > The dataset property on the HTMLOrForeignElement interface provides read/write access to all the custom data attributes (data-*) set on the element. This access is available both in HTML and within the DOM. It is a map of DOMStrings, one entry for each custom data attribute.

let element = document.getElementById("test");
let footer = document.querySelector("#output");

/* get element values using camelCase names through .dataset */
let sample = element.dataset.sample;
let sampleNumber = element.dataset.sampleNumber;

let dataFromElement = sample + " :: " + sampleNumber;

footer.innerHTML = element.innerHTML  + dataFromElement;

<input type="hidden" id="test" data-sample="Sample" data-sample-number=34 />
<div id="output"> </div>

Although there are concerns about Internet Explorer support and performance on this you can check here.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTony the PonyView Question on Stackoverflow
Solution 1 - JavascriptJamesView Answer on Stackoverflow
Solution 2 - JavascriptAndy EView Answer on Stackoverflow
Solution 3 - Javascriptmeder omuralievView Answer on Stackoverflow
Solution 4 - JavascriptmikefreyView Answer on Stackoverflow
Solution 5 - Javascriptmorris4View Answer on Stackoverflow
Solution 6 - JavascriptbcoscaView Answer on Stackoverflow
Solution 7 - JavascriptniiimaView Answer on Stackoverflow