12

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
  • 378,754
  • 76
  • 643
  • 1,055
Kryštof Hilar
  • 609
  • 2
  • 10
  • 22

1 Answers1

12

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
  • 151,816
  • 78
  • 307
  • 352
Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
  • 2
    `elem.dataset.customVariable` is also possible with `data-` attributes - might be a bit cleaner. – pimvdb Dec 21 '11 at 18:34