Skip to content

Instantly share code, notes, and snippets.

@6502
Created October 24, 2016 08:41
Show Gist options
  • Save 6502/bb76088e72481bbdad2bf28d6456e6c4 to your computer and use it in GitHub Desktop.
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")))
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