Reputation: 59
I am trying to create a page that creates 5 random DIVS using javascript. For some reason it only works when I have any content before the <!doctype html>
tag on my page which makes no sense to me. Any insight as to what I am doing wrong?
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<div id = "boxHouse">
</div>
<script>
var divNum = 1;
for (x = 0; x<5; x++){
var boxDiv = document.getElementById("boxHouse");
var newElm = document.createElement("div");
newElm.id = divNum;
newElm.style.width = Math.floor((Math.random()*100)+2);
newElm.style.height = Math.floor((Math.random()*100)+2);
newElm.style.border = "thin solid black";
newElm.style.backgroundColor = "#FF0000";
divNum++
boxDiv.appendChild(newElm);
}
</script>
</body>
</html>
Upvotes: 0
Views: 102
Reputation: 25595
Your code will work if you add units to the width and height:
newElm.style.width = Math.floor((Math.random()*100)+2) + "px";
newElm.style.height = Math.floor((Math.random()*100)+2) + "px";
The reason this is needed is a css size without a unit is discarded, so the divs are empty and thus you can only see their borders stacked as a thin black bar at the top of the page.
EDIT: the reason it works if you add something before the doctype is that then the browser goes into quirks mode (as opposed to standards-compliant mode with the doctype) where it is a lot more accepting of non-standard things like broken css units.
Upvotes: 2