175

Custom data attributes: http://dev.w3.org/html5/spec/Overview.html#embedding-custom-non-visible-data

When I say “work”, I mean, if I’ve got HTML like this:

<div id="geoff" data-geoff="geoff de geoff">

will the following JavaScript:

var geoff = document.getElementById('geoff');
alert(geoff.dataGeoff);

produce, in IE 6, an alert with “geoff de geoff” in it?

Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270
  • 117
    HTML5 and IE6? The horror... O_o – Vivin Paliath Mar 09 '10 at 22:11
  • Hey, the doctype works at least. Small mercies. – Paul D. Waite Mar 09 '10 at 22:13
  • 7
    Note that `data-geoff` isn't a valid JS identifier due to the "-" character. You'd need to use `dataGeoff` in scripts. – outis Mar 09 '10 at 22:25
  • @outis: note that `geoff.dataGeoff` won't work, it's `undefined`. – Marcel Korpel Mar 09 '10 at 23:16
  • @Marcel: that's a different matter, the matter of the question. My comment was only addressing the syntax issue. – outis Mar 10 '10 at 20:12
  • @outis: Although I understand your point (about a non-valid identifier), your comment could imply that every HTML attribute with a hyphen in it can be translated to camel-case. That's only true for CSS style properties, as far as I know. – Marcel Korpel Mar 10 '10 at 22:30
  • @Marcel: it's also true of HTML5 data attributes (I had to check this myself). Whether the browser supports it is another matter. – outis Mar 10 '10 at 23:42
  • 3
    @outis: According to the specs (in draft), you mean? I tested this myself in FF 3.6 and Chromium 5.0.307.11 and retrieving `geoff.dataGeoff` didn't work. It turned out (http://www.whatwg.org/specs/web-apps/current-work/multipage/elements.html#embedding-custom-non-visible-data) that it *should* be `geoff.dataset.geoff`, but as `element.dataset` is still `undefined` in modern browsers, that's neither supported. – Marcel Korpel Mar 11 '10 at 00:24
  • +1 for the Eddie Izzard reference. – weenoid May 03 '12 at 08:40
  • Is geoff de geoff an Eddie Izzard reference? I never knew that. – Paul D. Waite May 03 '12 at 13:48
  • 7
    The jeffth of the jeffth, nineteen jeffty-jeff. – Matt Sach Jul 27 '12 at 16:38
  • @outis for knowledge's sake, it is possible to do `foo['invalid-name']` where one would want to do `foo.invalid-name` but couldn't. – ANeves Aug 08 '12 at 18:53
  • 2
    @ANeves: while that allows one to access a property with non-identifier characters, it doesn't apply here as the browser won't bridge a 'data-geoff' HTML attribute with a property of the same name in the DOM. – outis Aug 13 '12 at 05:46
  • 1
    @outis I could get it at `elem.attributes['data-geoff'].value`: http://jsfiddle.net/MEaVR/1/ (It even works in IE8.) – ANeves Aug 13 '12 at 09:24
  • 2
    @ANeves: note that that's basically the same as Marcel's answer of using `getAttribute`, as it uses the DOM rather than HTML5 data attributes. Looks like a useful addition to his answer, though. – outis Aug 15 '12 at 19:21
  • If the browser is really working with DOM tree - which I hope all do - you can theoretically have any element with any attributes, like and work with them as with standard elements & attributes. – jave.web Feb 01 '14 at 11:11
  • @jave.web: sure, but invented elements/attributes 1. might have unwanted effects if they’re later supported by browsers; 2. have no globally-agreed semantics, unlike standard HTML; and 3. preclude you from using a non-customised HTML validator to check your HTML for errors. None of those might be a big deal for a given situation, but they’re at least worth thinking about. – Paul D. Waite Feb 01 '14 at 12:59
  • @PaulD.Waite Totally agree with you Paul ! :) I was just stating the reason why it works :) – jave.web Feb 01 '14 at 13:12
  • @jave.web: ah, yes I see, with you. – Paul D. Waite Feb 01 '14 at 13:13

6 Answers6

154

You can retrieve values of custom (or your own) attributes using getAttribute. Following your example with

<div id="geoff" data-geoff="geoff de geoff">

I can get the value of data-geoff using

var geoff = document.getElementById("geoff");
alert(geoff.getAttribute("data-geoff"));

See MSDN. And although it is mentioned there that you need IE7 to get this to work, I tested this a while ago with IE6 and it functioned correctly (even in quirks mode).

But this has nothing to do with HTML5-specific attributes, of course.

Marcel Korpel
  • 21,536
  • 6
  • 60
  • 80
  • 4
    Totally, this isn’t actual support of HTML5 data attributes. Does sound like a way to utilise them though. – Paul D. Waite Mar 09 '10 at 23:05
  • Correct this doesn't support the API of data putting things in a collection or whatever (nobody supports this yes). However, as shown by get/Set Attribute you can get the main use of data- attributes immediately in any minimally DOM aware browser. You probably also could monkey patch browsers if you are so inclined to make the missing collections. From my recent book experiments it is clear that data- attributes are usable now and are far superior to the current common scheme of overloading the class attribute value to contain style info and random meta data. – Thomas Powell Mar 10 '10 at 21:42
  • “ You probably also could monkey patch browsers if you are so inclined to make the missing collections.” — Yeah, that’s the nice thing about JavaScript as compared to CSS: because it’s a programming language, you can fix compatibility issues yourself. – Paul D. Waite Mar 10 '10 at 22:22
  • I'm actually amazed this answer still gets so much credit, especially as IE 6 should be considered "dead", according to many web developers. – Marcel Korpel Jul 22 '11 at 11:13
  • 6
    @Marcel: I think quite a few sites still have IE 6 as a non-negligible part of their audience. Maybe in *another* 10 years we won’t have to worry any more. – Paul D. Waite Sep 08 '11 at 16:05
140

Yes, they work.

IE has supported getAttribute() from IE4 which is what jQuery uses internally for data().

data = elem.getAttribute( "data-" + key ); // Line 1606, jQuery.1.5.2.js

So you can either use jQuery's .data() method or plain vanilla JavaScript:

Sample HTML

<div id="some-data" data-name="Tom"></div>

Javascript

var el = document.getElementById("some-data");
var name = el.getAttribute("data-name");
alert(name);

jQuery

var name = $("#some-data").data("name");
Marko
  • 71,361
  • 28
  • 124
  • 158
  • 2
    This answer seems to conflict a bit with canIuse. Any input on why it's marked as "partially" supported? http://caniuse.com/dataset – Snekse Jun 04 '13 at 19:54
  • 8
    @Snekse I believe it's related to the note at the bottom `Note: All browsers can already use data-* attributes and access them using getAttribute. "Supported" refers to accessing the values using the dataset property. Current spec only refers to support on HTML elements, only some browsers also have support for SVG/MathML elements.` – Marko Jun 04 '13 at 22:51
  • @Marko What about `
    ` , would this be ok in IE6 ? How would you read the value ?
    – Royi Namir Oct 28 '15 at 12:46
  • @RoyiNamir I believe it should work OK with any attribute but you best check. I don't have IE6 handy anywhere. – Marko Oct 28 '15 at 21:02
  • I wish jquery would just go away – SuperUberDuper Apr 11 '16 at 12:50
  • Someone should update MDN because it says getAttribute support dates back to IE 8 and according to you it dates back to IE 4. I know for a fact it works in IE 6 so I do not doubt that you are correct and that MDN is wrong as often it is. I find that frustrating since it is supposed to be an authoritative source. – PHP Guru Sep 26 '20 at 14:35
9

Not only does IE6 not support the HTML5 Data Attribute feature, in fact virtually no current browser supports them! The only exception at the moment is Chrome.

You are perfectly at liberty to use data-geoff="geoff de geoff" as an attribute, but only Chrome of the current browser versions will give you the .dataGeoff property.

Fortunately, all current browsers - including IE6 - can reference unknown attributes using the standard DOM .getAttribute() method, so .getAttribute("data-geoff") will work everywhere.

In the very near future, new versions of Firefox and Safari will start to support the data attributes, but given that there's a perfectly good way of accessessing it that works in all browsers, then there's really no reason to be using the HTML5 method that will only work for some of your visitors.

You can see more about the current state of support for this feature at CanIUse.com.

Hope that helps.

Spudley
  • 166,037
  • 39
  • 233
  • 307
  • 1
    "Not only does IE6 not support the HTML5 Data Attribute feature, in fact virtually no current browser supports them" - sure, although that does depend on your definition of "support". No browser supports the `dataset` property, but all browsers allow you to store data in attributes with a prefix of `data-`, and (as you say) retrieve it via `getAttribute`. So in one sense they support the feature, because you can use the attributes themselves effectively. – Paul D. Waite Jun 28 '11 at 14:24
  • I see your point about there being no reason to use the `dataset` property to access them though - I don't know what benefits it's supposed to offer over `getAttribute`. – Paul D. Waite Jun 28 '11 at 14:25
  • 2
    @Paul -- it doesn't offer any advantages over getAttribute. What it offers is a standardised way to handle storing data against a tag using attributes. This has always worked but was never an official standard until HTML5. HTML5 simply took an existing non-standard but widely used feature and ratified it, adding some rules to say how you should name them, and defining a new way to access them. When I say it's not supported, I'm explicitly referring to the `.dataXYZ` properties; as you say, the basic functionality is widely supported, but not because it's HTML5. – Spudley Jun 28 '11 at 15:15
7

I think IE has always supported this (at least starting from IE4) and you can access them from JS. They were called 'expando properties'. See old MSDN article

This behaviour can be disabled by setting the expando property to false on a DOM element (it's true by default, so the expando properties work by default).

Edit: fixed the URL

Esteban
  • 162
  • 8
Timores
  • 14,439
  • 3
  • 46
  • 46
4

If you wanted to retrieve all of the custom data attributes at once like the dataset property in newer browsers, you could do the following. This is what I did and works great for me in ie7+.

function getDataSet(node) {
    var dataset = {};
    var attrs = node.attributes;
    for (var i = 0; i < attrs.length; i++) {
        var attr = attrs.item(i);
        // make sure it is a data attribute
        if(attr.nodeName.match(new RegExp(/^data-/))) {
            // remove the 'data-' from the string 
            dataset[attr.nodeName.replace(new RegExp('^data-'), '')] = attr.nodeValue;
        }
    }
    return dataset;
}
user1767210
  • 603
  • 6
  • 5
0

In IE6, it may not work. For reference: MSDN

I suggest using jQuery to handle most of the cases:

var geoff = $("#geoff").data("data-geoff");
alert(geoff);

Try this in your coding.

Dan
  • 10,282
  • 2
  • 37
  • 64
HTML5 developer
  • 237
  • 3
  • 2