Last active
October 13, 2015 03:57
-
-
Save nornagon/4135553 to your computer and use it in GitHub Desktop.
3l33t javascript tag creation
This file contains hidden or 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
tag = (name, text) -> | |
parts = name.split /(?=[.#])/ # why yes, i am a ninja | |
tagName = "div" | |
classes = [] | |
id = undefined | |
for p in parts | |
switch p[0] | |
when '#' then id = p.substr 1 | |
when '.' then classes.push p.substr 1 | |
else tagName = p | |
element = document.createElement tagName | |
element.id = id if id? | |
element.classList.add c for c in classes | |
element.innerText = text if text | |
element |
This file contains hidden or 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
function tag(name, text) { | |
var parts = name.split(/(?=[.#])/); // why yes, i am a ninja | |
var tagName = "div", id, classes = []; | |
for (var i = 0; i < parts.length; i++) { | |
var p = parts[i]; | |
switch (p[0]) { | |
case '#': id = p.substr(1); break; | |
case '.': classes.push(p.substr(1)); break; | |
default: tagName = p; | |
} | |
} | |
var element = document.createElement(tagName); | |
if (typeof id !== 'undefined') | |
element.id = id; | |
for (var i = 0; i < classes.length; i++) { | |
element.classList.add(classes[i]); | |
} | |
if (text) | |
element.innerText = text; | |
return element; | |
} |
This file contains hidden or 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
var main = document.body.appendChild(tag('#main')) | |
main.appendChild(tag('nav#side.left')) | |
main.appendChild(tag('aside.right')) | |
main.appendChild(tag('button.big.red#attack', 'Fire the lasers!')) | |
// document.createElement is such a drag! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment