Alex Rivera | Logout

Can I add arbitrary properties to DOM objects?

Asked 2010-11-23T16:41:10.957
70

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?

Edit
Report

2 Answers

33

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

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");
answered 2010-11-23T16:43:02.997
8

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';
answered 2010-11-23T16:45:06.650

Your Answer