Show HN: A better way of writing HTML via JavaScript?
Something along the lines of:
const req = await fetch('api.com/posts')
const data = await req.json()
for (const d of data)
createPost(d)
For that, I end up writing this piece of code const assignDeep = (elm, props) => Object.entries(props).forEach(([key, value]) =>
typeof value === 'object' ? assignDeep(elm[key], value) : Object.assign(elm, {[key]: value}))
const $c = (tag, props = {}, children = []) => {
const elm = document.createElement(tag)
assignDeep(elm, props)
elm.append(...children)
return elm
}
that way, I can define a blog post like this: const div = $c('div', {className: 'blog-post'}, [
$c('h1', {innerText: 'My blog post'}),
$c('div', {className: 'body'}, [
$c('p', {innerText: 'My first blog post'})
]),
$c('div', {className: 'footer'}, [
$c('span', {innerText: 'Author: '}, [
$c('a', {href: '#', innerText: 'atum47'})
]),
$c('span', {innerText: 'Date: ' + new Date().toLocaleString()})
])
]);
Here's an JS Fiddle of that code - https://jsfiddle.net/victorqribeiro/5cketz40/I think this is a simple and elegant way to create HTML elements in JavaScript reducing the verbose of calling document.createElement() and element.append() everywhere. What do you think?