Plugin parade #1: metadata

A common problem when developing web applications is to provide some data from your server-side to client-side scripts. Consider a client-side form validation: You don’t want to generate tons of inline scripts and you don’t want to dynamically generate your javascript files. So you need a way to provide and read metadata from the HTML markup. And of course as unobtrusive as possible.

After a longer discussion about this matter on the jQuery mailing list, John Resig developed the initial version of the metadata plugin. Afterwards, Yehuda Katz wrote the first documentation and I improved both some more and wrote some tests.

Metadata plugin source (requires jQuery 1.0.4+, contains detailed documentation)
Metdata Testsuite
Documentation on Visual jQuery (Plugins/Metadata), though a bit outdated

The default usage is to put javascript objects inside the class attribute of your elements. Once the metadata plugin is loaded and you access an element, the plugin reads the data and provides it as a property on the element.

I’m using the plugin for the yet-to-be-released version of my validation plugin. You define an input that requires an email address to be entered with this code:

<input id="email" name="email" class="{email:true}" />

The validation plugin searches for all input elements inside the form that it validates and reads the metadata via the data() method:

data = $(element).data();

I highly recommend using the class attribute for metadata. As long as you put the data inside {}-brackets and avoid any spaces, you won’t produce any problems with stylesheets. And according to the HTML specification, the purpose of the class attribute is for both CSS classes and other data.


No more comments.
  1. I’ve seen this plugin now, and it seems very good.

    Anyway, the class method suffers the spaces problem, in a subtle way. This page will show a red welcome:

    .a {color:red;}
    <p class=”{b:’ a ‘}”>Hello World</p>

    this means that any word can clash with an existing CSS class: not only identifiers, but also words inside properly quoted string values.

  2. Good point Andrea. Unfortuanetely, the other two methods have both their own, in my opinion, worse drawbacks.

    So you just have to make sure that use to many spaces.

    The already mentioned validation plugin has an equalTo method. As the parameter, you define the element to compare to via a jQuery expression. This worked fine:


    But it could cause trouble with a bit more complex expressions.

  3. Hi,

    Just wanted to let you know about a bug I found on your Metadata plugin.

    Details of the bug:

    Details of the fix:

    This fix has worked for myself and 2 other people.

    Diego A.

  4. @Diego: It looks like I’ve fixed that just a few days ago. Check my comment on the bug report:

    Let me know if that works for you too!