Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding variables to DOM elements

Tags:

javascript

dom

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

like image 821
Kryštof Hilar Avatar asked Dec 21 '11 18:12

Kryštof Hilar


1 Answers

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>
like image 52
Adam Rackis Avatar answered Oct 11 '22 06:10

Adam Rackis