views:

41

answers:

5

Possible Duplicate:
Can I just make up attributes on my HTML tags?

Hi,

I am not sure if what I am asking is even possible, but I'd like to be able to add a custom (nonrendered) propery to an existing HTML DOM node.

For example, if I have a simple DOM as below:

<body>
 <p>
  <span id="aSpan"></span>
 </p>
</body>

.. I'd like to be able to add a custom property to the span 'aSpan' to store a numeric variable.

Is this possible and if so, what is the best way to do it?

Thanks,

A: 

Not necessarily the most purist way, but innerHTML allows you to manipulate the many of the DOM elements directly.

nonnb
I need to store the variable in such a way as to not have it shown to the user. I'd sooner not add invisible text to my element if I can get away with it.
Konrad
But it is not at all related to set attributes.
Felix Kling
A: 

Sure, I do this all the time. You can do it in the html:

<span id="aSpan" attname="attvalue">

(validators don't like this though, technically it's not valid html but it works)

Or via javascript:

element.setAttribute('attname', 'attvalue');

You can read it with:

element.getAttribute('attname');

Rob
A: 

I'm not sure in plain Javascript, but jQuery has the data function.

$('#aSpan').data('foo', 69);

alert($('#aSpan').data('foo')); 
fearofawhackplanet
A: 

a simple way.. if your page is dinamic.. you can simply add a value to your ID

a little example if I understand well, you can use it in a class, supposed we have a 56 has ID

<body>
 <p>
  <span id="aSpan" class="A54F23345A56A23524234"></span>
 </p>
</body>

I do simply made a string the ID 'A54F23345A' + 56 + 'A23524234'

But you can use it has you wish.. and the id is hidden from users.. you can use more secure script.. but if isn't a security issue.. it works like a charm ^^

Have a nice day

Paper-bat
+1  A: 

Take a look at the duplicate question for reasons why not to do this this and restrictions on how it can be done legally in HTML 5.

Despite the validation errors you'll receive, using jQuery you can make use of the $.attr() function:

$('.element').attr('foo', 'bar')
Nathan Taylor