10

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,

Community
  • 1
  • 1
Konrad
  • 39,751
  • 32
  • 78
  • 114
  • 2
    See [Can I just make up attributes on my HTML tags?](http://stackoverflow.com/questions/427262/can-i-just-make-up-attributes-on-my-html-tags) – Matthew Flaschen Jul 29 '10 at 14:25

4 Answers4

17

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
  • 8,042
  • 3
  • 35
  • 37
  • 3
    depending on your doctype this may be invalid. It's better to use the HTML5 `data-attname="blah"` – p3drosola Sep 05 '12 at 11:48
  • 1
    Well this was answered in 2010, but you are correct, I now always prepend 'data-' to custom attribute names. – Rob Sep 18 '12 at 07:32
2

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')
Community
  • 1
  • 1
Nathan Taylor
  • 24,423
  • 19
  • 99
  • 156
1

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

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

alert($('#aSpan').data('foo')); 
fearofawhackplanet
  • 52,166
  • 53
  • 160
  • 253
0

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

Massimo
  • 553
  • 7
  • 24