Created
October 24, 2016 08:41
-
-
Save 6502/bb76088e72481bbdad2bf28d6456e6c4 to your computer and use it in GitHub Desktop.
Utility to create a DOM element with prescribed style, parent and content (e.g. x=e("div#mydiv.myclass", {s_border:"solid 1px #000"}, "textnode", e("#inner")))
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
function e(type, opts) { | |
var i; | |
if (!opts) opts = {}; | |
i = type.indexOf("."); | |
if (i >= 0) { opts.className = type.slice(i+1); type = type.slice(0, i); } | |
i = type.indexOf("#"); | |
if (i >= 0) { opts.id = type.slice(i+1); type = type.slice(0, i); } | |
var d = document.createElement(type||"div"); | |
if (opts.className) d.className = opts.className; | |
if (opts.id) d.id = opts.id; | |
if (opts.parent) opts.parent.appendChild(d); | |
Object.keys(opts).forEach(function(k){ | |
if (k !== "parent" && k !== "className" && k !== "id") { | |
if (k.slice(0, 2) == "s_") { | |
d.style[k.slice(2)] = opts[k]; | |
} else { | |
d[k] = opts[k]; | |
} | |
} | |
}); | |
Array.prototype.slice.call(arguments, 2).forEach(function(c) { | |
if (typeof c === "string") { | |
d.appendChild(document.createTextNode(c)) | |
} else { | |
d.appendChild(c); | |
} | |
}); | |
return d; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment