I was trying to create function to create a div and style it, here is the code: http://jsfiddle.net/NGnEd/5/.
<script type="text/javascript">
var dom = {
// Build the main button
buildButton: function(){
// Create new DOM element - div
var button = document.createElement('div');
// Set element attribute
button.setAttribute('id', 'newElement');
// Style the element
button.style.width = "100px";
button.style.height = "100px";
// Add content
button.innerHTML = 'new Element';
// Print element
document.body.innerHTML += button;
}
}
</script>
<div onclick="dom.buildButton();">
The first div
</div>
It is supposed to create element, style it, add content and print it. But it’s not working, I don’t know the reason.
Any help?
You can’t add an HTML element to a string. Instead of
Try
Also, as noted by @Felix Kling, you set up the JSFiddle incorrectly, so
onclick="dom.buildButton"does not work. Working example here:http://jsfiddle.net/pnHRp/1/