Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to add metadata to HTML elements

I'm trying to put together a way of marking up various components in HTML that get parsed by a jQuery script and created when the page loads.

For example, at the moment I can put the following in to my page..

<a href="link.html" class="Theme-Button Theme-Button-Style-win2007 Theme-Button-iconLeft Theme-Button-AlignmentCenter Theme-Button-fullWidth">This is a button</a>

When the jQuery script finds it it'll inject the html necessary to create a button with an icon on it and all the necessary events etc.

However, this is messy and requires a lot of long class names. I'd much rather do something like this...

<a href="#" class="Theme-Button" data="{style: 'win2007', icon: 'left', align:'center', fullWidth: true}"></a>

It's not that much shorter but neater in my opinion and requires less parsing. Trouble is, I've done a little bit of research into "expandos" and I'm fairly sure some browsers won't like it and it won't validate.

Anybody got any better suggestions?

like image 252
jonhobbs Avatar asked Dec 17 '09 17:12

jonhobbs


People also ask

How do you add metadata to HTML?

The <meta> tag defines metadata about an HTML document. Metadata is data (information) about data. <meta> tags always go inside the <head> element, and are typically used to specify character set, page description, keywords, author of the document, and viewport settings.

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.

Is HTML a metadata element?

<meta>: The metadata element. The <meta> HTML element represents metadata that cannot be represented by other HTML meta-related elements, like <base> , <link> , <script> , <style> or <title> . Metadata content.


2 Answers

Go ahead and use an attribute for this, but use a data- prefix on it. Attributes with the prefix data- are explicitly allowed on all elements as of HTML5. Example:

<a href="#" class="Theme-Button" data-theme="{style: 'win2007', icon: 'left', align:'center', fullWidth: true}"></a>

It works today in all browsers, and because it's now specified behavior, it's future-proofed.

like image 137
T.J. Crowder Avatar answered Oct 01 '22 15:10

T.J. Crowder


Use jquery's ".data" property. This is very handy and many people don't know about it.

See this link for more information.

like image 23
Patrick Karcher Avatar answered Oct 01 '22 16:10

Patrick Karcher