最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Adding variables to DOM elements - Stack Overflow

programmeradmin5浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 13

I 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>
发布评论

评论列表(0)

  1. 暂无评论