Skip to content

Instantly share code, notes, and snippets.

@thebearingedge
Created May 3, 2022 00:01
Show Gist options
  • Save thebearingedge/ed30065346117baa1bd53b717dabe229 to your computer and use it in GitHub Desktop.
Save thebearingedge/ed30065346117baa1bd53b717dabe229 to your computer and use it in GitHub Desktop.
DOM creation helper function.
function h(tagName, attributes, ...children) {
if (arguments.length === 2) {
if (Array.isArray(attributes) || typeof attributes !== 'object') {
children = [attributes]
attributes = null
}
}
const $element = document.createElement(tagName)
for (const name in attributes) {
$element.setAttribute(name, attributes[name])
}
$element.append(...children.flat())
return $element
}
const $pokemon =
h('div', { class: 'column-third' }, [
h('div', { class: 'pokemon-card' }, [
h('img', { src: 'https://bit.ly/39xXwqa' }),
h('div', { class: 'card-text' }, [
h('h2', 'Pikachu'),
h('h3', '#025'),
h('p', 'Has cheek sacs that are extra soft and super stretchy.')
])
])
])
console.log($pokemon)
/**
* <div class="column-third">
* <div class="pokemon-card">
* <img src="https://bit.ly/39xXwqa">
* <div class="card-text">
* <h2>Pikachu</h2>
* <h3>#025</h3>
* <p>Has cheek sacs that are extra soft and super stretchy.</p>
* </div>
* </div>
* </div>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment