简体   繁体   中英

HTML Custom Attributes Not Working in Chrome

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.

Retrieving it via getAttribute():

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

Works fine for me across IE, FF and Chrome.

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:

Got same problem for Safari and using getAttribute(..) made the magic. It looks like cross browser compatible. Here is nice article http://www.javascriptkit.com/dhtmltutors/customattributes.shtml

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM