Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

So what if custom HTML attributes aren't valid XHTML?

I know that is the reason some people don't approve of them, but does it really matter? I think that the power that they provide, in interacting with JavaScript and storing and sending information from and to the server, outweighs the validation concern. Am I missing something? What are the ramifications of "invalid" HTML? And wouldn't a custom DTD resolve them anyway?

like image 210
Constantine Avatar asked Jun 15 '09 07:06

Constantine


People also ask

Can you use custom HTML attributes?

Custom attributes are attributes that are not part of the standard HTML5 attributes but are explicitly created. They allow us to add our own information to HTML tags. These are not specific and can be used with all the HTML elements.

Do HTML attributes need values?

We Suggest: Always Quote Attribute ValuesThe HTML standard does not require quotes around attribute values. However, W3C recommends quotes in HTML, and demands quotes for stricter document types like XHTML.


2 Answers

The ramification is that w3c comes along in 2, 5, 10 years and creates an attribute with the same name. Now your page is broken.

HTML5 is going to provide a data attribute type for legal custom attributes (like data-myattr="foo") so maybe you could start using that now and be reasonably safe from future name collisions.

Finally, you may be overlooking that custom logic is the rational behind the class attribute. Although it is generally thought of as a style attribute it is in reality a legal way to set custom meta-properties on an element. Unfortunately you are basically limited to boolean properties which is why HTML5 is adding the data prefix.

BTW, by "basically boolean" I mean in principle. In reality there is nothing to stop you using a seperator in your class name to define custom values as well as attributes.

class="document docId.56 permissions.RW"

like image 62
SpliFF Avatar answered Sep 17 '22 21:09

SpliFF


Yes you can legally add custom attributes by using "data".

For example:

<div id="testDiv" data-myData="just testing"></div> 

After that, just use the latest version of jquery to do something like:

alert($('#testDiv').data('myData')) 

or to set a data attribute:

$('#testDiv').data('myData', 'new custom data') 

And since jQuery works in almost all browsers, you shouldn't have any problems ;)

update

  • data-myData may be converted to data-mydata in some browsers, as far as the javascript engine is concerned. Best to keep it lowercase all the way.
like image 29
DrParanoia Avatar answered Sep 20 '22 21:09

DrParanoia