Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@CoolDeavil CoolDeavil commented Dec 5, 2015

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