Skip to content Skip to sidebar Skip to footer

Generate Random Number Of Divs

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

Solution 1:

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

Solution 2:

1) You closed the "generateDiv function" in the wrong place, move the closing bracket from before the "var divs" to after the "var divs" loop.

2) You are altering all the existing divs in the DOM: var divs = document.getElementsByTagName("div"); Don't do that, use dfrag.

3) Like Matthew said, you have to add dfrag to the DOM.

Solution 3:

functiongenerateDiv(){
  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);
  }
  for (i = 0; i < dfrag.childNodes.length; i++) {
    div = dfrag.childNodes[i];
    alterDivStyle(div);
  }
  document.body.appendChild(dfrag);
}
functionrndColor() {
  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); // bluereturn'#' + r + g + b;
}

functiongenerateRandom(min, max) {
  var number = Math.floor(Math.random() * (max - min )) + min;
  return number;
}
functionalterDivStyle(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>";
};  
generateDiv();

Post a Comment for "Generate Random Number Of Divs"