views:

788

answers:

3

When using HTML custom attributes it doesn't works in Chrome.

What I mean is, suppose I have this HTML:

<div id="my_div" my_attr="1"></div>

If I try to get this attribute with JavaScript in Chrome, I get undefined

alert( document.getElementById( "my_div" ).my_attr );

In IE it works just fine.

+2  A: 

IE is about the only browser I've seen that honor attributes that do not conform to the HTML DTD schema.

http://www.webdeveloper.com/forum/showthread.php?t=79429

However, if you're willing to write a custom DTD, you can get this to work.

This is a good article for getting started down that direction:

altCognito
A: 

Are you declaring your page as XHTML compliant? You can't add new attributes to elements willy-nilly if you do. My understanding is that there are ways (after all, ASP.NET succeeds at it), but you have to emit all kinds of gunk (custom schema?). I'm not familiar with the details.

Euro Micelli
+9  A: 

Retrieving it via getAttribute():

alert(document.getElementById( "my_div" ).getAttribute("my_attr"));

Works fine for me across IE, FF and Chrome.

Paul Roub
+1. Works in Opera 9.6 and Safari 4 for Windows as well.
Grant Wagner