Skip to content

Instantly share code, notes, and snippets.

@boof
Last active December 15, 2015 18:09
Show Gist options
  • Save boof/5302251 to your computer and use it in GitHub Desktop.
Save boof/5302251 to your computer and use it in GitHub Desktop.
jQuery Zen API
// Examples:
/* RADAR
* Since the current CSS selector parsing algorithm does not support quoted
* commas it'll be replaced with the Slick CSS Selector Parser.
*/
Zen();
// document.createElement('div');
Zen.default = 'span';
Zen();
// document.createElement('span');
$.Z('a.resource[href="/index.html"]').text('Home')
// $('<a href="/index.html" class="resource">Home</a>')
$.Z('ul.items').z('li#item-1, li#item-2');
// $('<ul class="items">').append( $('<li id="item-1">').add('<li id="item-2">') )
// TODO Write some tests.
// Copyright 2013 Florian Aßmann; Licensed MIT
;(function(_, $, undef) {
"use strict";
function each(ary, callback) {
for (var i = 0, ii = ary.length; i < ii; i++) {
var obj = ary[i];
callback.call(obj, i, obj);
}
}
var zenAttributes = /\[([\w-]+)=([^\]]+)\]/g;
var zenChoosen = /\s*,\s*/g;
var zenPath = /\s*>\s*/g;
function build(selector) {
var nodeName, nodeId, nodeClass, node, attributes = {};
selector = selector.replace(zenAttributes, function(m, key, value) {
attributes[key] = /^"/.test(value) ?
value.substring(1, value.length - 1) :
value;
return '';
});
selector = selector.split('.');
nodeClass = selector.slice(1).join(' ');
selector = selector[0].split('#', 2);
nodeName = selector[0] || 'div';
nodeId = selector[1];
if (nodeId) { attributes.id = nodeId; }
if (nodeClass) { attributes.class = nodeClass; }
node = document.createElement(nodeName);
$(node).attr(attributes);
return node;
}
function Zen(selector) {
var nodes = [];
selector = selector || Zen.default;
each(selector.split(zenChoosen), function() {
var node;
each(this.split(zenPath), function() {
var child = build(this);
if (node) node.appendChild(child);
node = child;
});
nodes.push(node);
});
return nodes;
}
Zen.default = 'div';
_.Zen = Zen;
$.Z = function(selector) {
return $( Zen(selector) );
};
$.fn.z = function(selector) {
return this.append( Zen(selector) );
};
})(this, jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment