Created
September 5, 2012 14:17
-
-
Save Couto/3637328 to your computer and use it in GitHub Desktop.
create DOM Elements through a CSS Selector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* $$ - 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; | |
}; | |
}()); |
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
⚡ you my friend.... are awesome ! ⚡