Last active
November 5, 2018 21:48
-
-
Save js2me/0b36b43275c2b57fb53d61bf11bcec2a to your computer and use it in GitHub Desktop.
compact dom helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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