Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append custom attributes to a DOM node [duplicate]

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,

like image 920
Konrad Avatar asked Jul 29 '10 14:07

Konrad


3 Answers

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');

like image 173
Rob Avatar answered Oct 24 '22 17:10

Rob


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')
like image 2
Nathan Taylor Avatar answered Oct 24 '22 17:10

Nathan Taylor


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

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

alert($('#aSpan').data('foo')); 
like image 1
fearofawhackplanet Avatar answered Oct 24 '22 19:10

fearofawhackplanet