Skip to content

Instantly share code, notes, and snippets.

@elmahdim
Created December 28, 2015 10:43
Show Gist options
  • Save elmahdim/5daf33bfe2843721ce81 to your computer and use it in GitHub Desktop.
Save elmahdim/5daf33bfe2843721ce81 to your computer and use it in GitHub Desktop.
Generate an element object in vanilla javascript
/*
* @usage generateElement(_tagName, _attributes, _parent);
* @param _tagName:String
* @param _attributes:Object
* @param _parent:Selector
* @return an element object
* @author Mahmoud Elmahdi
*/
function generateElement(_tagName, _attributes, _parent) {
Element.prototype.setAttributes = function(attrs) {
for (var idx in attrs) {
if ((idx == 'styles' || idx == 'style') && typeof attrs[idx] == 'object') {
for (var prop in attrs[idx]) {
this.style[prop] = attrs[idx][prop]
}
} else if (idx == 'html') {
this.innerHTML = attrs[idx]
} else {
this.setAttribute(idx, attrs[idx]);
}
}
};
var $tag = document.createElement(_tagName);
$tag.setAttributes(_attributes);
_parent.appendChild($tag);
return $tag;
}
// Example
generateElement('div', {
'id': 'my-id',
'class': 'my-class',
'styles': { /* CSS Properties */ },
'html': 'text goes here...'
},
document.body);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment