-
-
Save tmrk/bdd9aacff09a4ff1c5f606d6e814e9f4 to your computer and use it in GitHub Desktop.
Simple HTML node creator in JavaScript
This file contains 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
// Node creator, usage: n('tag#id.class|attribute=value', text/[children], {event: function() {...}) | |
const n = (tag, content, listener) => { | |
let el = document.createElement(tag.split('#')[0].split('.')[0].split('|').shift() || 'div'); | |
if (tag.split('#')[1]) el.id = tag.split('#')[1].split('.')[0].split('|')[0]; | |
if (tag.split('.')[1]) el.classList.add(...tag.split('.').slice(1).join('.').split('|')[0].split('.')); | |
if (tag.split('|')[1]) { | |
let attrTemp = tag.split('|').slice(1); | |
for (let i = 0; i < attrTemp.length; i++) el.setAttribute(attrTemp[i].split('=')[0], attrTemp[i].split('=')[1]); | |
} | |
if (content) { | |
if (typeof content === 'string' || typeof content === 'number') { | |
el.insertAdjacentHTML('beforeend', content); | |
} | |
else if (content.constructor === Array) for (let i = 0; i < content.length; i++) { | |
if (typeof content === 'string' || typeof content === 'number') { | |
el.insertAdjacentHTML('beforeend', content[i]); | |
} else el.appendChild(content[i]); | |
} | |
else el.appendChild(content); | |
} | |
if (listener) for (let event in listener) if (listener.hasOwnProperty(event)) el.addEventListener(event, listener[event]); | |
return el; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've been using this little helper for a while now. I wrote it to make HTML element creation easier in smaller projects where a library is not needed,
It supports basic element creation with id, class and attributes, specifying children (or an array of children), and inline binding of multiple event listeners.
It does have its limitations, especially if an element tree gets too big, but for simple projects it does the job well and with practically no overhead.
Here is an example on how to use it: