Skip to content

Instantly share code, notes, and snippets.

@tmrk
Created June 7, 2022 08:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmrk/bdd9aacff09a4ff1c5f606d6e814e9f4 to your computer and use it in GitHub Desktop.
Save tmrk/bdd9aacff09a4ff1c5f606d6e814e9f4 to your computer and use it in GitHub Desktop.
Simple HTML node creator in JavaScript
// 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;
}
@tmrk
Copy link
Author

tmrk commented Jun 7, 2022

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:

document.body.appendChild(
  n('#app', [
    n('label|for=myname', 'Name'),
    n('input#myname.names.right|type=text|placeholder=Enter your name', '', {
      input: (e) => { console.log(e.target.value); }, // using an arrow function
      blur: function () { console.log('Your name: ' + this.value); }  // using 'this' with a regular function
    })
  ])
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment