Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.)

like image 725
Hemant Avatar asked Aug 20 '09 12:08

Hemant


People also ask

Can I add my own attributes to HTML elements?

If you want to define your own custom attributes in HTML, you can implement them through data-* format. * can be replaced by any of your names to specify specific data to an element and target it in CSS, JavaScript, or jQuery.

Can I add two attributes to HTML elements?

The multiple attribute in HTML allows user to enter more than one value. It is a Boolean attribute and can be used on <input> as well as <select> element, To allow multiple file uploads in HTML forms, use the multiple attribute. The multiple attribute works with email and file input types.

Can an attribute be applied multiple times to the same element?

It is not valid to have the same attribute name twice in an element.

Can a HTML element have multiple data attributes?

You can have multiple data attributes on an element and be used on any HTML element.


1 Answers

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)

like image 84
Paolo Bergantino Avatar answered Sep 19 '22 22:09

Paolo Bergantino