Created
December 28, 2015 10:43
-
-
Save elmahdim/5daf33bfe2843721ce81 to your computer and use it in GitHub Desktop.
Generate an element object in vanilla javascript
This file contains hidden or 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
/* | |
* @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