Skip to content

Instantly share code, notes, and snippets.

@maburdi94
Last active April 26, 2021 17:33
Show Gist options
  • Save maburdi94/b03da10c96650ae19eb6d78e7202c4d9 to your computer and use it in GitHub Desktop.
Save maburdi94/b03da10c96650ae19eb6d78e7202c4d9 to your computer and use it in GitHub Desktop.
Shorthand to create an HTML element in Vanilla JS using selector syntax for tag, id, and classes.
function tag(selector, attrs, innerText = '') {
let _tag = selector.match(/^(\w[\w-_\d]*)/)?.[1];
let _id = selector.match(/#([\w_]+[\w-_\d]*)/)?.[1];
let _classes = Array.from(selector.matchAll(/\.([\w_]+[\w-_\d]*)/g)).map(m => m?.[1]);
let el = document.createElement(_tag ?? 'div');
if (_id) {
el.setAttribute('id', _id);
}
if (_classes) {
el.classList.add(..._classes);
}
if (attrs) {
for (let [attr, value] of Object.entries(attrs)) {
el.setAttribute(attr, value);
}
}
el.innerText = innerText;
return el;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment