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 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..
Share Improve this question edited Dec 21, 2011 at 18:26 Lightness Races in Orbit 385k77 gold badges665 silver badges1.1k bronze badges asked Dec 21, 2011 at 18:23 Kryštof HilarKryštof Hilar 6392 gold badges10 silver badges22 bronze badges 2- possible duplicate of Can I add arbitrary properties to DOM objects? – Lightness Races in Orbit Commented Dec 21, 2011 at 18:28
- 1 stackoverflow./questions/7895560/… is a better Q&A – Lightness Races in Orbit Commented Dec 21, 2011 at 18:29
1 Answer
Reset to default 13I think that will work, but the more mon 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>