Skip to content

Instantly share code, notes, and snippets.

@emkamal
Last active June 7, 2017 12:02
Show Gist options
  • Save emkamal/2e78ea08847ac625b87a53202e3b60e2 to your computer and use it in GitHub Desktop.
Save emkamal/2e78ea08847ac625b87a53202e3b60e2 to your computer and use it in GitHub Desktop.
function to create dom in a more concise way
var createDom = function (tag, config)
{
var elem = document.createElement(tag);
if (config) {
for (var key in config) {
if (key !== "attrs" && key !== "events" && key !== "styles" && key !== "options" && key !== "parent") {
elem[key] = config[key];
}
}
for (var key in config.attrs) {
elem.setAttribute(key, config.attrs[key]);
}
for (var key in config.styles) {
elem.style[key] = config.styles[key];
}
for (var key in config.events) {
elem.addEventListener(key, config.events[key])
}
if (tag == "select" && config.options) {
for (var key in config.options) {
var option = createDom("option", { innerHTML: config.options[key].text, attrs: { "value": config.options[key].value } });
if (config.options[key].selected) {
option.setAttribute("selected", "selected");
}
elem.appendChild(option);
}
}
if (config.parent) config.parent.appendChild(elem);
}
return elem;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment