0

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>
2
  • 2
    what do you mean with 'any content before the tag' ? Commented Mar 6, 2014 at 3:44
  • Sorry, it got lost, it only displays the divs correclty if I add any character before the doctype tag Commented Mar 6, 2014 at 3:45

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Yep. That's exactly what was wrong with it. Thank you so much. I will never make that mistake again
I just saw your edit on the post and added some more details to this too. Adding stuff before the doctype makes the doctype not count; it turns off standards mode and the browser is more accepting of non-standard code quirks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.