Skip to content

Instantly share code, notes, and snippets.

@kaitwalla
Last active May 31, 2020 05:38
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 kaitwalla/e39efcb0fabe66c4dc6bfe017ddc02ac to your computer and use it in GitHub Desktop.
Save kaitwalla/e39efcb0fabe66c4dc6bfe017ddc02ac to your computer and use it in GitHub Desktop.
Small vanilla JS helper to create DOM elements with one command
function DomEl(creationString) {
var elType = creationString.match(/^(\w+)*/g);
var classes = creationString.match(/\.([^\s\.\#\[]*)/g);
var id = creationString.match(/\#([^\s\.\[]*)/g);
var attributes = creationString.match(/\[([^\]]*)/g);
if (elType) {
var el = document.createElement(elType);
if (classes && classes.length > 0) {
for (var i = 0; i < classes.length; i++) {
el.classList.add(classes[i].replace('.',''));
}
}
if (attributes && attributes.length > 0) {
for (var i = 0; i < attributes.length; i++) {
var attribute = attributes[i].split('=');
if (attribute.length == 1) {
attribute.push('');
} else {
attribute[1] = attribute[1].replace(/"/g,'');
}
attribute[0] = attribute[0].replace('[','');
if (['title','href'].indexOf(attribute[0]) > -1) {
el[attribute[0]] = attribute[1];
}
el.setAttribute(attribute[0],attribute[1]);
}
}
if (id && id.length == 1) {
el.id = id.replace('#','');
}
return el;
} else {
return false;
}
}
/* Usage:
new DomEL('div.class') returns a DOM element of <div class="class"></div>
new DomEl('a[href="/link"].btn#bigButton.btn-primary[data-weird="yes"]') =
<a href="/link" class="btn btn-primary" id="bigButton" data-weird="yes"></a>
*/
export default DomEl;
class DomEl {
constructor(creationString) {
this.elType = creationString.match(/^(\w+)*/g);
this.classes = creationString.match(/\.([^\s\.\#\[]*)/g);
this.id = creationString.match(/\#([^\s\.\[]*)/g);
this.attributes = creationString.match(/\[([^\]]*)/g);
if (this.elType) {
this.el = document.createElement(this.elType);
if (this.classes && this.classes.length > 0) {
for (var className of this.classes) {
this.el.classList.add(className.replace('.',''));
}
}
if (this.attributes && this.attributes.length > 0) {
for (var attributeString of this.attributes) {
let attribute = attributeString.split('=');
if (attribute.length == 1) {
attribute.push('');
} else {
attribute[1] = attribute[1].replace(/"/g,'');
}
attribute[0] = attribute[0].replace('[','');
if (['title','href'].indexOf(attribute[0]) > -1) {
this.el[attribute[0]] = attribute[1];
}
this.el.setAttribute(attribute[0],attribute[1]);
}
}
if (this.id && this.id.length == 1) {
this.el.id = this.id.replace('#','');
}
return this.el;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment