0

I would like to get the value of custom attributes. For exemple, for this:

<div style="-my-data:3;" id="foo" ></div>

I would like to write something like that:

document.getElementById("foo").style.myData;

But it's not working. How can I do?

Vladimir Starkov
  • 19,264
  • 8
  • 60
  • 114
user1365010
  • 3,185
  • 8
  • 24
  • 43
  • 1
    possible duplicate of [Can I access the value of invalid/custom CSS properties from JavaScript?](http://stackoverflow.com/questions/2926326/can-i-access-the-value-of-invalid-custom-css-properties-from-javascript) – James Allardice Jun 13 '12 at 15:10
  • Use jQuery? Though in all seriousness it has a `data()` method... – tskuzzy Jun 13 '12 at 15:11
  • Do I still just write `
    `?
    – user1365010 Jun 13 '12 at 15:13
  • @user1365010 I'm not sure **every** browser will replace "myData" with "-my-data". You better use document.getElementById("foo").style["-my-data"] – Adriano Repetti Jun 13 '12 at 15:16
  • it doesn't work too : http://jsfiddle.net/Afu8b/ – user1365010 Jun 13 '12 at 15:20
  • @user1365010 the "style" property is associated with the inline style attribute, it's empty for CSS rules. Moreover the current behavior is...undefined if the CSS rule is unknown by the browser (so you may get "undefined" or empty string) – Adriano Repetti Jun 13 '12 at 15:46
  • Side question: why do you want to put some custom data inside the CSS? Can't you use custom attributes as posted in answers? Is there a special reason? – Adriano Repetti Jun 13 '12 at 15:48

3 Answers3

3

You should be using HTML5's custom data-* attributes instead:

<div data-myDataName="3" id="foo"></div>

Then, to get it via JavaScript, just use this:

document.getElementById('foo').getAttribute('data-myDataName'); // '3'

Here's the fiddle: http://jsfiddle.net/c55nf/


P.S. Even though it's part of HTML5, it'll still work in older browsers. It was just standardized in HTML5.

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
2

use the html data attribute:

<div data-style="3" id="foo"></div>

and then use

document.getElementById("foo").getAttribute("data-style");

to retrieve the information

Luca
  • 9,259
  • 5
  • 46
  • 59
0

Use HTML custom data attributes:

HTML:

<div data-myval="3" id="foo" ></div>​

JavaScript

alert(document.getElementById("foo").getAttribute('data-myval'));​

See the fiddle.

Jason McCreary
  • 71,546
  • 23
  • 135
  • 174