Skip to content

Instantly share code, notes, and snippets.

@richtr
Created February 3, 2012 14:25
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 richtr/1730398 to your computer and use it in GitHub Desktop.
Save richtr/1730398 to your computer and use it in GitHub Desktop.
DOM Element Constructor wrapper
/**
* DOM Element constructor helper class.
*
* Usage:
* -------
* var newDiv = Element.create('div');
* var newDiv = Element.create('div', {text: "Hi"});
* var newDiv = Element.create('div', {text: "Hi "}, [
* Element.create('span', {style: 'color: #CC0000', html:"<b>you</b>"}, [
* // Infinitely chainable
* ])
* ]);
*
*/
(function( window ) {
var document = window.document;
var _Element = window.Element || {};
_Element.create = function( tag, props, children ) {
var el = document.createElement( tag );
if ( props ) {
_Element.setAttributes( el, props );
}
if ( children ) {
for ( var i = 0, l = children.length; i < l; i += 1 ) {
el.appendChild( children[i] );
}
}
return el;
};
_Element.setAttributes = function( el, props ) {
for ( var prop in props ) {
if ( props.hasOwnProperty( prop ) ) {
var name = _Element.attributeNameMap[ prop ],
value = props[ prop ];
if ( value ) {
if ( name ) {
el[ name ] = value;
} else {
el.setAttribute( prop, value );
}
}
}
}
};
_Element.attributeNameMap = {
'className': 'className',
'for': 'htmlFor',
html: 'innerHTML',
text: 'textContent'
};
window.Element = _Element;
})( window );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment