I would like to ask, if is 'legal' to add custom variables to document body elements. For example:
document.getElementById('elem1').customVariable = 'xxx';
This code just work, but i don't know if it is 'allowed'
It doesn't appear in list of tag's arguments, but variable is usable in further code..
I think that will work, but the more common way to add custom attribute is like this:
<div id="elem1" data-customVariable="foo"
And then
document.getElementById('elem1').setAttribute("data-customVariable", "bar");
Or if older browser choke on setAttribute
document.getElementById('elem1')["data-customVariable"] ="bar";
EDIT
Thanks to pimvdb for pointing out that you can also do
document.getElementById('elem1').dataset.customVariable ="bar";
Just note that you'll have to watch how you name this -- the camel casing can throw it off. You'll want
<div id="elem1" data-custom-variable="xxx"></div>
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