views:

103

answers:

3

Hello! First post on stackoverflow. Hope everything is right!

I'm thinking of attaching an ID value to the HTML element itself via JavaScript, instead of using the HTML id attribute.

For instance, say that JavaScript variable htmlElement is a div. So htmlElement.cssName would tell us its CSS class.

Now, how about doing

htmlElement.idProperty = "someValue"

in JavaScript instead of doing <div id="someValue">? Then I can use the idProperty in say event handlers.

this.idProperty

That simple!

Is there something wrong in doing so?

EDIT: Thanks for yor answers! Very helpful and instructive. I wish I could check green on all of them!

+1  A: 

You can use the createAttribute method to add an id to the element like this:

id = document.createAttribute('id');
id.value = "someValue";
htmlElement.setAttributeNode(id);
Andrew Hare
I prefer using `setAttribute`: `htmlElement.setAttribute("id", "someValue");` - http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level-one-core.html#ID-F68F082
NickFitz
+2  A: 

no, you can do it the way you like it, if you are dynamically creating this item you should use this method, if you are doing this inside html I recommend you to just put the name of the id in html too.

However a small note. Use element.id instead of idProperty.

element.id = 'my-id';
Tomh
A: 

What you're doing there is adding a runtime property (in your case, called idProperty) to an HTMLElement object instance. You can get away with doing that in your JavaScript code (the Prototype library does it all the time). Makes me uncomfortable, but it does work on all major browsers.

If you want to be able to specify these in HTML markup as well, though, I'd use attributes instead. You can create attributes with any names you want, although to be careful I'd use names like data-xyz (e.g., use a data- prefix) as that's the HTML5 standard way of using your own attributes. Then you use getAttribute to get the value and setAttribute to set/update the value.

T.J. Crowder