Skip to content

Instantly share code, notes, and snippets.

@Couto
Created September 5, 2012 14:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Couto/3637328 to your computer and use it in GitHub Desktop.
Save Couto/3637328 to your computer and use it in GitHub Desktop.
create DOM Elements through a CSS Selector
/**
* $$ - Creates a DOM Element with the given attributes
*
* @author Luis Couto <couto@15minuteslate.net> (https://github.com/Couto)
* @license MIT (http://couto.mit-license.org)
*
* @function
* @param {String} selector CSS Selector representing the HTML and attributes
* @returns {Node} HTML Element
*
* @example
* $$('div#body.enabled.fluid[data-binding="true"][disabled="true"]')
* // Returns
* <div id="body" class="enabled fluid" data-binding="true" disabled="true"></div>
*/
var $$ = (function () {
'use strict';
var idRegex = /\#(\w+)/i,
classNameRegex = /\.(\w+)/ig,
elementRegex = /^(\w+)/i,
attributesRegex = /\[([a-z\-]+)\s*=\s*("|')*(\w+)("|')*\]/ig;
return function (selector) {
var elId = idRegex.exec(selector),
elClassName = classNameRegex.exec(selector),
elTagName = elementRegex.exec(selector),
elAttributes = attributesRegex.exec(selector),
classNames = "",
el;
if (elTagName) {
el = document.createElement(elTagName[1]);
if (elId) { el.id = elId[1]; }
while (elClassName) {
classNames += elClassName[1] + " ";
elClassName = classNameRegex.exec(selector);
}
if (classNames) { el.className = classNames; }
while (elAttributes) {
el.setAttribute(elAttributes[1], elAttributes[3]);
elAttributes = attributesRegex.exec(selector);
}
}
idRegex.lastIndex = 0;
elementRegex.lastIndex = 0;
classNameRegex.lastIndex = 0;
attributesRegex.lastIndex = 0;
return el;
};
}());
@jonasfrey
Copy link

⚡ you my friend.... are awesome ! ⚡

@jonasfrey
Copy link

althouth i would inject this on line 36 , to have the div tagName as default fallback
if(elTagName == null){ elTagName = ["",["div"]]; }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment