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,
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');
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')
I'm not sure in plain Javascript, but jQuery has the data function.
$('#aSpan').data('foo', 69);
alert($('#aSpan').data('foo'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With