Skip to content

Instantly share code, notes, and snippets.

@Ayehavgunne
Last active July 30, 2017 19:35
Show Gist options
  • Save Ayehavgunne/19e262fd8adf65a989e1e168866a6082 to your computer and use it in GitHub Desktop.
Save Ayehavgunne/19e262fd8adf65a989e1e168866a6082 to your computer and use it in GitHub Desktop.
Programmatically create html tags
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'));
}
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