Is it OK to add your own attributes to HTML elements? [duplicate]

Possible Duplicates:
Custom attributes - Yay or nay?
Non-Standard Attributes on HTML Tags. Good Thing? Bad Thing? Your Thoughts?

In current learning project I am working on, I need to add an attribute whose value will be a number. At first I thought of using "id" for this purpose but an answer revealed that it is not good to do that.

Is it OK if I create my own attribute, say "messid" and assign a numeric value such as "12", "6" etc to it?

Here is why I want to do this so that you can correct me if I am doing it totally wrong: I need to access this number in my JavaScript (using jQuery). Just taking the value of attribute is easy but extracting the numeric value from a string like "m12" or "m6" is a pain. (I am a beginner in JavaScript world.)


There has been much discussion about this:

  • Custom attributes - Yay or nay?
  • How to store arbitrary data for some HTML tags
  • Non-Standard Attributes on HTML Tags. Good Thing? Bad Thing? Your Thoughts?

At the end of the day, I am on the camp that believes data attributes are the best way to go. They are being introducted in HTML5 to avoid name conflicts. Essentially, if you want to store anything data related you just prepend "data-" on the attribute name:

<div class="user" data-userid="5"></div>

The only con to the whole thing is then that your XHTML won't validate, but I honestly don't care about that stuff. (That's right, I said it)


In HTML 5 you're allowed to add any attribute starting with data-, so e.g. <div data-messid="12"> is OK.

HTML 4 and XHTML 1 won't validate if you add your own attribute, but besides that nothing bad will happen if you choose attribute name unique enough (so it won't conflict with any current or future HTML attribute).


Just so you know, you can easily extract an ID from a string like m12 or m6, I would do it like this:

//name the IDs m_12, m_3 etc
var number = $('#someElement').attr('id').split('_')[1];

Or if say, you have a bunch of links with numbers in the ID as above, and all the links have the clickMe class:

$('a.clickMe').click(function() {
    alert($(this).attr('id').split('_')[1]);
});

I use custom attributes, and since they are supported by all browsers I checked I think it is not bad to use them. You can also use custom HTML tags to simulate HTML5, with some IE hack, so why not use attributes, if they don't need any hacks?

Anyway, you can read similar discussion here: Custom attributes - Yea or nay?