Skip to content

Instantly share code, notes, and snippets.

@jgusta
Last active July 1, 2024 06:15
Show Gist options
  • Save jgusta/3bc0033ae4c970e5ceaf1b7242383759 to your computer and use it in GitHub Desktop.
Save jgusta/3bc0033ae4c970e5ceaf1b7242383759 to your computer and use it in GitHub Desktop.
DOM Tag Factory
const tf = function (attachPoint) {
const root = globalThis || window
const dom = root.document || document
function selectEl(el) {
if (el.ELEMENT_NODE) {
return el
}
else {
return dom.querySelector(el)
}
}
let attach
if (attachPoint) {
attach = selectEl(attachPoint)
}
else {
attach = false
}
const HTML_NS = "http://www.w3.org/1999/xhtml"
const SVG_NS = "http://www.w3.org/2000/svg"
const funcs = {
before(el) {
el = selectEl(el)
el.insertAdjacentElement('beforebegin', this)
return this
},
after(el) {
el = selectEl(el)
el.insertAdjacentElement('afterend', this)
return this
},
begin(el) {
el = selectEl(el)
el.insertAdjacentElement('afterbegin', this)
return this
},
end(el) {
el = selectEl(el)
el.insertAdjacentElement('beforeend', this)
return this
}
}
function tagFactory(NS, tagName) {
return function pork (...args) {
let element = attach ? attach : dom.createElementNS(NS, tagName)
Object.assign(element, funcs)
function flatten(e) {
if (e !== null && e !== "") {
if (e.forEach) {
e.forEach(flatten)
} else {
if (e instanceof Node) {
element.append(e)
} else if (e instanceof Object) {
for (let k in e) {
let v = e[k]
if (v !== null) {
let evname = (/^on(.+)$/.exec(k) || [])[1]
if (evname) {
element.addEventListener(evname, v)
} else if (k === "style") {
for (let ks in v) {
element.style[ks] = v[ks]
}
} else {
element.setAttribute(k, v)
}
}
}
} else {
element.append(dom.createTextNode(e))
}
}
}
}
flatten(args)
return element
}
}
const html = new Proxy(
{ },
{
get: (target, name) =>
name in target ? target[name] : tagFactory(HTML_NS, name),
}
)
return html
}
const h = ft().html

const output = h.div(h.div(h.h1('Title Page'),h.div({class: 'some class names', justattribute:""},'Hello')))

console.log(output)

Output:

<div>
  <div>
    <h1>Title Page</h1>
    <div class="some class names" justattribute>
      Hello
    </div>
  </div>
</div>

Attach to something

output.begin(h.div('woah').begin('body'))

Build off of an existing element



Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment