-
-
Save jonathanvoelkle/6e4d4888ec74a9b3a0d73a2ba96a26fd to your computer and use it in GitHub Desktop.
A tiny helper for document.createElement.
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
| function createElement(options) { | |
| let el; | |
| if (!options.tagName) { | |
| el = document.createDocumentFragment(); | |
| } else { | |
| el = document.createElement(options.tagName); | |
| if (options.className) { | |
| el.className = options.className; | |
| } | |
| if (options.attributes) { | |
| for (let a in options.attributes) { | |
| el.setAttribute(a, options.attributes[a]); | |
| } | |
| } | |
| if (options.on) { | |
| for (var e in options.on) { | |
| el.addEventListener(e, options.on[e]); | |
| } | |
| } | |
| if (options.style) { | |
| for (let s in options.style) { | |
| elem.style[s] = options.style[s]; | |
| } | |
| } | |
| if (options.innerHTML) { | |
| el.innerHTML = options.innerHTML; | |
| } | |
| } | |
| if (options.text) { | |
| el.appendChild(document.createTextNode(options.text)); | |
| } | |
| // IE 8 doesn't have HTMLElement | |
| if (window.HTMLElement === undefined) { | |
| window.HTMLElement = Element; | |
| } | |
| if (options.childs && options.childs.length) { | |
| let child; | |
| for (let i = 0; i < options.childs.length; i++) { | |
| child = createElement(options.childs[i]); | |
| if (child instanceof window.HTMLElement) { | |
| el.appendChild(child); | |
| } | |
| } | |
| } | |
| return el; | |
| } | |
| module.exports.default = createElement; |
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 createElement from './createElement'; | |
| document.body.appendChild(createElement({ | |
| tagName: 'div', | |
| className: 'my-class', | |
| text: 'Blah blah', | |
| attributes: { | |
| 'id': 'element id', | |
| 'data-truc': 'value' | |
| }, | |
| on: { | |
| 'click': () => { | |
| console.log('Blah !') | |
| } | |
| }, | |
| innerHTML: '<b>Bold</b>', | |
| style: { | |
| color: 'blue', | |
| backgroundColor: 'black' | |
| }, | |
| // recursive call | |
| childs: [{ | |
| tagname: 'i', | |
| text: 'Italic' | |
| }, { | |
| tagname: 'p', | |
| text: 'just normal text' | |
| }] | |
| })) | |
| // if you use without tagName you will get a document fragment |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment