Skip to content

Instantly share code, notes, and snippets.

@tzi
Created February 20, 2012 11:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tzi/1868872 to your computer and use it in GitHub Desktop.
Save tzi/1868872 to your computer and use it in GitHub Desktop.
A #javaScript #function : Create HTML element

If you want to try it, go here

This function use innerHTML. This is not the fastest way not the cleanest, but the simplest.

function createElement( str ) {
var elem = document.createElement('div');
elem.innerHTML = str;
if ( elem.childNodes.length > 0 ) {
return elem.childNodes[0];
}
return elem;
}
function addImportantStyle( el, styles ) {
var style = '';
for ( var i=0; i<styles.length; i++ ){
if ( styles[i][ styles[i].length-1 ] == ';' ) {
styles[i] = styles[i].substr( 0, styles[i].length-1 );
}
style += styles[i] + ' !important;';
}
el.setAttribute( 'style', style );
}
<!DOCTYPE html>
<html>
<head>
<title>Create HTML node easily</title>
<script type="text/javascript" src="create_element.js"></script>
<script type="text/javascript">
window.onload = function() {
document.getElementById( 'button' ).onclick = function() {
var div = createElement( '<div class="x-widget"><a href="#" title="coco">coco</a></div>' );
addImportantStyle( div, [
'float: left',
'width: 200px',
'height:200px',
'line-height: 200px',
'background-color: #CCCCCC',
'text-align: center'
]);
document.body.appendChild( div );
div.onclick = function() { alert( 'coco' ); };
return false;
}
}
</script>
</head>
<body>
<button id="button">Add element</button>
<br/>
</body>
</html>
@CoolDeavil
Copy link

Thanks for posting, I was looking to find a clear example on this subject. Very nice.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment