Last active
July 30, 2017 19:35
-
-
Save Ayehavgunne/19e262fd8adf65a989e1e168866a6082 to your computer and use it in GitHub Desktop.
Programmatically create html tags
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 _create_html(inner_html, attributes = {}, data_attr = {}, self_closing = false, tag = null) { | |
let html = '<' + tag | |
if (!is_array(inner_html) && is_object(inner_html)) { | |
attributes = inner_html | |
inner_html = null | |
} | |
for (let key in attributes) { | |
html = html + ' ' + key + '="' + attributes[key] + '"' | |
} | |
for (let key in data_attr) { | |
html = html + ' data-' + key + '="' + data_attr[key] + '"' | |
} | |
if (self_closing && !inner_html) { | |
html = ' />' | |
} | |
else { | |
html = html + '>' | |
if (inner_html) { | |
if (inner_html.constructor === Array) { | |
for (let elem of inner_html) { | |
html = html + elem | |
} | |
} | |
else { | |
html = html + inner_html | |
} | |
} | |
html = html + '</' + tag + '>' | |
} | |
return html | |
} | |
function tag(tag, inner_html = null, attributes = {}, data_attr = {}, self_closing = false) { | |
return _create_html(inner_html, attributes, data_attr, self_closing, tag) | |
} | |
function tag_factory(tag) { | |
return function (inner_html, attributes = {}, data_attr = {}, self_closing = false) { | |
return _create_html(inner_html, attributes, data_attr, self_closing, tag) | |
} | |
} | |
function is_array(val) { | |
return val instanceof Array | |
} | |
function is_object(val) { | |
if (val === null) { | |
return false | |
} | |
return ((typeof val === 'function') || (typeof val === 'object')); | |
} |
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
let th = tag_factory('th') | |
console.log(create_tag('thead', create_tag('tr', [th('hello'), th('hola', {class: 'big_text'}), th('hi')]), {class: 'hide'})) | |
// outputs | |
// <thead class="hide"><tr><th>hello</th><th class="big_text">hola</th><th>hi</th></tr></thead> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment