Skip to content

Instantly share code, notes, and snippets.

@devinrhode2
Created June 5, 2012 22:36
Show Gist options
  • Save devinrhode2/2878569 to your computer and use it in GitHub Desktop.
Save devinrhode2/2878569 to your computer and use it in GitHub Desktop.
A better createElement function, that takes a map of
//turns this:
var button = document.createElement('img');
button.src = 'images/button.png';
button.id = 'button';
button.className = 'button';
//to this:
var button = $.createElement('img', {
src: 'images/button.png',
id: 'button',
className: 'thatOneButton'
});
//with this:
$.createElement = function createElement(element, props, attributes) {
var element = document.createElement(element);
if (typeof props !== 'undefined') {
for (var prop in props) {
element[prop] = props[prop];
}
if (typeof attributes !== 'undefined') {
for (var attr in attributes) {
element.setAttribute(attr, attributes[attr]);
}
}
}
return element;
};
/*And it doesn't break the current document.createElement function!
If the 2nd param is gone, then it just returns the normal element!*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment