10

I have to choose between custom data tags or ids. I would like to choose custom data tags, but I want to be sure that they do not cause browser compatibility issues for the most widely used browsers today.

I'm using jQuery 1.6 and my particular scenario involves a situation where I need to reference a commentId for several actions.

<div data-comment-id="comment-1" id="comment-1">
   <a class="foo"></a>
</div>

It's easier to extract data tags in jQueryin: $('foo').data('commentId');

Extract a substring from the id seems a bit complicated and could break for one reason or another: <a id="comment-1"

Are there any sweeping merits or fatal flaws for either approach?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Mohamad
  • 34,731
  • 32
  • 140
  • 219
  • 1
    Custom data attributes don't validate under XHTML 1 or HTML 4, although that's nothing to do with browser compatibility - I believe they (like much of HTML5) were designed to work without causing issues in older browsers (i.e. IE). – Paul D. Waite Jun 28 '11 at 13:50
  • Related: http://stackoverflow.com/questions/3974139/what-happens-if-you-use-custom-attribute-in-a-html-tag?rq=1 – Ciro Santilli OurBigBook.com Jan 31 '14 at 11:20

2 Answers2

6

I would advise in favor of data attributes for the following reasons:

  • ids need to be unique document-wide. Thus they are limited in the semantics they can carry
  • you can have multiple data-attributes per element

and probably less relevant in your case:

  • changing ids might break idrefs

However, I'm not sure whether I understand your specs completely as extracting the element id in jQuery is as trivial as getting the data attribute: $('.foo').attr('id');.

You might be interested in Caniuse.com, a browser compatibility site for web technologies.

If XHTML is an issue to you, you might also be interested in how to use custom data attributes in XHTML: see here for a discussion on SO and here for an XHTML-compatible approach using namespaces.

TylerH
  • 20,799
  • 66
  • 75
  • 101
collapsar
  • 17,010
  • 4
  • 35
  • 61
2

this guy says data attibutes work on IE6.

Community
  • 1
  • 1
Tom
  • 14,041
  • 16
  • 64
  • 80