Skip to content

Instantly share code, notes, and snippets.

@js2me
Last active November 5, 2018 21:48
Show Gist options
  • Save js2me/0b36b43275c2b57fb53d61bf11bcec2a to your computer and use it in GitHub Desktop.
Save js2me/0b36b43275c2b57fb53d61bf11bcec2a to your computer and use it in GitHub Desktop.
compact dom helper
import _ from 'lodash'
const dom = (query, asArray) =>
document[`querySelector${asArray ? 'All' : ''}`](query)
/*
dom.new('a', {
text: 'Click me!',
attrs: {
href: 'https://google.com',
},
classes: ['link', false && 'active'],
parent: dom('body'),
click: console.log,
})
*/
dom.new = (tag, { text, attrs, parent, classes, click }) => {
const element = document.createElement(tag)
if (!_.isEmpty(attrs))
_.each(attrs, (value, name) => element.setAttribute(name, value))
if (text) element.innerText = text
const compactedClasses = _.compact(classes)
if (compactedClasses.length)
_.each(compactedClasses, className => element.classList.add(className))
if (click) element.addEventListener('click', click)
if (parent) parent.appendChild(element)
return element
}
export default dom
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment