Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it considered bad practice to use non-standard HTML attributes? [duplicate]

I find it very convenient to set arbitary attributes like:

<a stackoverflowId="123">...</a>

And in JavaScript:

var soId = $selectofA.attr('stackoverflowId'); //jQuery

Is it a good practice at all? I've never had a problem with this yet.

like image 770
user198729 Avatar asked Jan 22 '10 14:01

user198729


3 Answers

In HTML 5 you can do this with the data-* attribute:

<a id="myDiv" data-stackoverflowId="123">...</a>

Since you are using jQuery, you may also want to check the jQuery Metadata Plugin. It will allow you to store and parse JSON metadata in the class attribute, and your markup will still validate.

You would be able to insert your metadata like this:

<a class="your_class {stackoverflowId: '123'}">...</a>

And extract it as follows:

var data = $selectofA.metadata();
like image 124
Daniel Vassallo Avatar answered Oct 18 '22 01:10

Daniel Vassallo


If you use data- attributes, it will at least be valid HTML5. See John Resig's blog post on the subject.

like image 22
Matchu Avatar answered Oct 17 '22 23:10

Matchu


I do this all the time, it works great. Never encountered any problem with this technique whatsoever. I suppose its not a bad idea though to use the data- prefix like suggested in some of the answers.

If you're really paranoid about standards compliance, you could write the HTML in a standard compliant manner and set the attributes on the DOM in a script. At least, the document will validate. But since the net result will be the same, you'd have to be pretty sick to favor that approach to the IMO natural way of extending html as it suits you.

Another approach is to write a custom DTD that defines exactly what extensions you want to use. This approach is described in detail here: http://www.alistapart.com/articles/customdtd/

Basically this approach relies on placing a modified copy of the XHTML DTD at some place, and using a doctype that points to that customized DTD. You would define the extra attribute declarations in that modified DTD, and apparently, the w3c validator will actually use that DTD to validate.

However, I would not use this approach for normal internet facing websites, ever. I'm afraid some browsers might go as far as trying to validate the doc against my dtd, but then give up with an error somewhere halfway. This custom DTD technique is not very widespread I simply wouldn't take the chance for regular webpages.

like image 35
Roland Bouman Avatar answered Oct 18 '22 01:10

Roland Bouman