Created
February 3, 2012 14:25
-
-
Save richtr/1730398 to your computer and use it in GitHub Desktop.
DOM Element Constructor wrapper
This file contains 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
/** | |
* 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