jquery.metadata.js – in reverse!

Stand back, kids!

This requires jQuery, jquery.metadata.js and jquery.json.js. You will also need to modify jquery.json.js so it surrounds JSON names and values in single quotes rather than doubles, and escapes single quotes, but this is trivial.

To use:

jQuery(selector).setadata({‘name’:'value’});

It will also chain your original selection.

/******************************************************************
Name: setadata
Description: Add metadata into elements - or metadata in reverse
Author: AK
Date: 24th June 2008
Version: 0.2
Dependencies: jQuery, jquery.metadata.js, jquery.json.js
Notes:
******************************************************************/
(function($) {
    $.fn.setadata = function(jsonData) {
        return this.each(function() {
			data = '{}';
			var m = /({.*})/.exec(this.className);
            if (m) {
				data = m[1];
				this.className = $.trim(this.className.replace(data, ''));
			}
			if (data.indexOf('{') < 0) data = "{" + data + "}";
            data = eval("(" + data + ")");
			for (var property in jsonData) {
				data[property] = jsonData[property];
			}
			this.className += ' ' + $.toJSON(data);
		});
    };
})(jQuery);

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>