I can't make the script to create random amount of divs. In this specific example between 5 and 20. The problem is in the for loop maybe? The function that generates random numbers is working correctly below in the random color function, I guess it is not recognized for some reasons. Also I am not getting any errors in firebug.
Example:
function generateDiv(){
var dfrag = document.createDocumentFragment();
var count = generateRandom(5, 20);
var i=0;
for (var i = 0; i < count; i++){
var div = document.createElement("div");
dfrag.appendChild(div);
}
}
var divs = document.getElementsByTagName("div");
for (i = 0; i < divs.length; i++) {
div = divs[i];
alterDivStyle(div);
}
function rndColor() {
var r = ('0' + generateRandom(0,255).toString(16)).substr(-2), // red
g = ('0' + generateRandom(0,255).toString(16)).substr(-2), // green
b = ('0' + generateRandom(0,255).toString(16)).substr(-2); // blue
return '#' + r + g + b;
}
function generateRandom(min, max) {
var number = Math.floor(Math.random() * (max - min )) + min;
return number;
}
function alterDivStyle(div){
div.style.width = generateRandom(20, 100) +"px";
div.style.height = generateRandom(20, 100) +"px";
div.style.backgroundColor = rndColor();
div.style.color = rndColor();
div.style.position = "absolute";
div.style.border = "solid";
div.style.borderColor = rndColor();
div.style.borderWidth = rndColor();
div.style.borderRadius = generateRandom(0, 10)+"px";
div.innerHTML = "<strong>div</strong>";
};
You never added the document fragment to the DOM
"DocumentFragments are DOM Nodes. They are never part of the main DOM tree. The usual use case is to create the document fragment, append elements to the document fragment and then append the document fragment to the DOM tree. In the DOM tree, the document fragment is replaced by all its children."
https://developer.mozilla.org/en-US/docs/Web/API/document.createDocumentFragment