11

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..

Lightness Races in Orbit
  • 369,052
  • 73
  • 620
  • 1,021
Kryštof Hilar
  • 539
  • 2
  • 7
  • 22

1 Answers1

11

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>
pimvdb
  • 146,912
  • 75
  • 297
  • 349
Adam Rackis
  • 81,646
  • 52
  • 262
  • 388
  • 2
    `elem.dataset.customVariable` is also possible with `data-` attributes - might be a bit cleaner. – pimvdb Dec 21 '11 at 18:34