Skip to content Skip to sidebar Skip to footer

How Do I Repeat Div Classes Using JavaScript Only?

Okay, I'm unsure how to word the question, but basically I want to repeat my div containers that have a class of 'blocks' using only javascript, no HTML (other than the HTML needed

Solution 1:

It's good you see the use of making a function of a re-occurring pattern.

Before posting it in StackOverflow, have you tried doing it yourself?

jsfiddle: http://jsfiddle.net/kychan/W7Jxu/

//    we will use a container to place our blocks.
//     fetch the element by id and store it in a variable.
var container = document.getElementById('container');

function block(mClass, html) {
    //extra html you want to store.
    return '<div class="' + mClass + '">' + html + '</div>';
}

//    code that loops and makes the blocks.
//    first part: creates var i
//    second:     condition, if 'i' is still smaller than three, then loop.
//    third part: increment i by 1;
for (var i = 0; i < 3; i++) {
    // append the result of function 'block()' to the innerHTML
    // of the container.
    container.innerHTML += block('block', 'data');
}

Edit: JS has changed a lot since the original post. If you do not require compatibility, use const, template literals, class and querySelector to make the code a bit cleaner. The following code has a Builder class and assumes there is a div with ID 'container':

// create class builder.
class Builder {
  //    create constructor, accept an element selector, i.e #container.
  constructor(targetContainerSelector) {
    //  search element by given selector and store it as a property.
    this.targetContainer = document.querySelector(targetContainerSelector);
  }

    //  method to append to innerHtml of target container.
  appendUsingInnerHtml(divAsHtml) {
    this.targetContainer.innerHTML += divAsHtml;
  }

  //    method to append to target container using DOM elements.
  appendUsingDom(divAsDom) {
    this.targetContainer.appendChild(divAsDom);
  }
}

//  constant to hold element selector.
const myTargetContainer = '#container';
//  constant to set the class if required.
const myDivClass = 'my-class';

//  constant to hold the instantiated Builder object.
const builder = new Builder(myTargetContainer);

//  loop 3 times.
for (let i=0; i<3; i++) {
  // call method to append to target container using innerHtml.
    builder.appendUsingInnerHtml(`<div class="${myDivClass}}">innerhtml div text</div>`);


  // OR.. build using DOM objects.

  //    create the div element.
  const div = document.createElement('div');

  //    create text element, add some text to it and append it to created div.
  div.appendChild(document.createTextNode('dom div text'));

  //    call method to append div DOM object to target container.
  builder.appendUsingDom(div);
}

Solution 2:

Please note: Every time something is added to the DOM, it forces the browser to reflow the DOM (computation of element's position and geometry).

Adding everything at once, improve speed, efficiency and performance of a code.

(ref: document.createDocumentFragment)

window.onload = Create();

function Create() {
          
   // create the container
   var mainContainer = document.createElement('div');
   mainContainer.id = 'mainContainer';
   // add all style in one go
   mainContainer.setAttribute('style', 'witdht: 400px; height: 200px; border: 2px solid green; margin-left: 20px;');

   
   var divBlocks1 = document.createElement('div');
   divBlocks1.className = 'blocks';
   divBlocks1.setAttribute('style', 'width: 100px; heigth: 100px; border: 1px solid black; margin-left: 20px; margin-top: 10px; floar: left;');

   var divBlocks2 = divBlocks1.cloneNode(false); // copy/clone above div
   var divBlocks3 = divBlocks1.cloneNode(false); // copy/clone above div
   
   // everything is still in memory
   mainContainer.appendChild(divBlocks1);
   mainContainer.appendChild(divBlocks2);
   mainContainer.appendChild(divBlocks3);
   
   // now we append everything to the document
   document.body.appendChild(mainContainer);

}

Good luck :)


Solution 3:

for(var d=0;d<10;d++){
   var aDiv = document.createElement('div');
       aDiv.className = "block";
   document.getElementsByTagName('body')[0].appendChild(aDiv);
}

Solution 4:

Rather than creating the elements before hand and then appending them to the main container, consider dynamically creating and appending them in a loop.

http://jsfiddle.net/TbCYH/6/

   for(var i = 0; i < 3; i++) {
       var divBlock = document.createElement("div");                
       divBlock.className = "blocks";
       mainContainer.appendChild(divBlock);       
   }

In the above code snippet a div is being created and appended for each iteration of the loop (which is set to cease at 3).

Also if possible, always use CSS classes rather than modifying the styles for each div directly.


Post a Comment for "How Do I Repeat Div Classes Using JavaScript Only?"