User Definable Attributes on HTML Elements?

dom, html, javascript

Solution

You can access your userdata="" attribute from JavaScript. Just do:

var theData = document.getElementById('item1').getAttribute('userdata');

If you want to do it the HTML5 way, then you would use attributes named data-*, e.g.:

<li id='item1' data-foo='This is element 1 from XYZ'>Item 1</li>

that way it will still be valid (i.e., it'll make you feel better for not using an invalid attribute). New browsers will support accessing the data-* attributes like so:

var theData = document.getElementById('item1').data.foo;

but I don't think that is implemented widely enough to rely upon yet.

If you do want to store the data in a comment (although I'd advise going the attribute route instead) you could do something like:

var e = document.getElementById('item1');
var n = e.firstChild;
while (n && n.nodeType != Node.COMMENT_NODE) {
    n = n.nextSibling;
}
// now n.nodeValue will have the comment contents

(No guarantees about whether IE likes any of the above.)

Problem

What I need to do is be able to store some piece of data about an element. For example, lets say I have a list item <li>, and I want to store some data about it in the element, like "This is element 1 from XYZ". The only way I know how to do this (which I don't want to do if I can avoid) is this: ``` <li id='item1'> Item 1 <!--This is element 1 from XYZ--> </li> <script> // read it something like this var e = document.getElementById('item1').innerHTML; // then parse out the comment, etc. // -- </script> ``` What I really want is something like this (which I am fairly certain is not possible): ``` // example <li id='item1' userdata='This is element 1 from XYZ'>Item 1</li> ``` .. of course, I would like to be able to access it somehow via javasscript. Alternatively, is there some other way to achieve this? Thanks -

Original source

Related problems