views:

1060

answers:

2

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?

+3  A: 

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 attribute to false on a DOM element (it's true by default, so the expando attributes work by default).

Edit: fixed the URL

Timores
Ah, yes sorry, I don’t think that’s the sense I intended. Just edited the question to clarify.
Paul D. Waite
I am the one being sorry, the link was wrong. It explained how to disable this behavior instead of explaining the feature. I've fixed the link and text.
Timores
getAttribute works cross-browser, no need to rely on IE quirks here.
foolip
@Timores: excellent, thank you. Nice article too, gotta love “Welcome to the first DHTML Dude column.”
Paul D. Waite
+8  A: 

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
Totally, this isn’t actual support of HTML5 data attributes. Does sound like a way to utilise them though.
Paul D. Waite
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
“ 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