-
-
Save olivmonnier/55f331e9c4b2316168c210ba1eea0036 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
| module.exports = function(options) { | |
| var el | |
| , a | |
| , i | |
| if (!options.tagName) { | |
| el = document.createDocumentFragment() | |
| } | |
| else { | |
| el = document.createElement(options.tagName) | |
| if (options.className) { | |
| el.className = options.className | |
| } | |
| if (options.attributes) { | |
| for (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.html !== undefined) { | |
| el.innerHTML = options.html | |
| } | |
| } | |
| 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) { | |
| for (i = 0; i < options.childs.length; i++) { | |
| el.appendChild(options.childs[i] instanceof window.HTMLElement ? options.childs[i] : createElement(options.childs[i])) | |
| } | |
| } | |
| return el | |
| } |
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
| var createElement = require("./createElement") | |
| document.body.appendChild(createElement({ | |
| tagName: "div", | |
| className: "my-class", | |
| text: "Blah blah", | |
| attributes: { | |
| "id": "element id", | |
| "data-truc": "value" | |
| }, | |
| on: { | |
| "click": function() { console.log("Blah !") } | |
| }, | |
| childs: [{ /* recursif call **/}] | |
| })) | |
| // 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