1

So I have a lot of divs in my markup look similar to:

<div class="container">
   <div class="wrapper">
      <h3>Title</h3>
      <p>Some text</p>
   </div>
</div>

The markup is look very messy and i'm fairly new to JS but wondering, if I could place all these divs into an array, then a for loop to iterate over them, then print them. But still have enough control over each div that I can change the background colour on them?

My JS so far:

  var div = {
    divInfo: [
      {
        title: "title",
        description: "Lorem ipsum dolor sit amet, consectetur adipiscing"
      }
    ]
  };

I've only shown one div at moment, as i'm still struggling with the for loop.

Any help/suggestions? Thanks!

5
  • Just use this document.getElementsByTagName('div'), then you can use for on it. Commented Jul 23, 2015 at 19:14
  • 2
    @MehdiDehghani That would require that the divs already exist (when the OP wants to create them from script), and that these were the only divs on the page. Also, working with the nested container/wrapper divs that way would be tough. Commented Jul 23, 2015 at 19:15
  • 1
    Use templates like handlebars Commented Jul 23, 2015 at 19:16
  • return value of document.getElementsByTagName is same as Array, but is live, that means if you add/remove div (using javascript, or via console), the result will be refreshed automatically. you need to provide an object and using for and fill the object. Commented Jul 23, 2015 at 19:18
  • 2
    To be clear, is your JavaScript writing the HTML to the page, just reading existing HTML, or reading and modifying existing HTML? Commented Jul 23, 2015 at 19:22

5 Answers 5

1

are you looking for something like this?

$(document).ready(function() {
    var arrayDivs = [
        {
            title: 'Title 1',
            description: 'This is the description to Title 1',
            backgroundColor: 'gray',
            color: 'black'
        },
        {
            title: 'Title 2',
            description: 'This is the description to Title 2',
            backgroundColor: 'blue',
            color: 'red'
        },
    ];
        
    function init() {
        for (var i = 0; i < arrayDivs.length; i++) {
            var html = '';
            html += '<div class="section" style="color:' + arrayDivs[i].color + '; background-color:' + arrayDivs[i].backgroundColor + ';">';
            html += '<h3>' + arrayDivs[i].title + '</h3>';
            html += '<p>' + arrayDivs[i].descritpion + '</p>';
            html += '</div>';
            $('.container').append(html);
        }
    };     
    init();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
   <div class="wrapper">
      <h3>Title</h3>
      <p>Some text</p>
   </div>
</div>

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

1 Comment

Why do you mix vanilla JS and JQuery to build the content? E.g. '<h3>' + arrayDivs[i].title + '</h3>' is a very bad example (c.f. XSS).
1

He I know JQuery you can do that with this

     var div = {
        divInfo: [
          {
            title: "Title 1",
            description: "1 Lorem ipsum dolor sit amet, consectetur adipiscing"
          },
          {
            title: "Title 2",
            description: "2 Lorem ipsum dolor sit amet, consectetur adipiscing"
          },
          {
            title: "Title 3",
            description: "3 Lorem ipsum dolor sit amet, consectetur adipiscing"
          },
          {
            title: "Title 4",
            description: "4 Lorem ipsum dolor sit amet, consectetur adipiscing"
          }        
        ]
      };
    
    $.each(div.divInfo,function(i,x){
     $('.container').append('<div class="wrapper"><h3>'+x.title+'<p>'+x.description+'</p></h3></div>')
    })
.wrapper{
    background:skyblue;
    margin:5px;
    padding:5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="container">
</div>

Comments

0

You can use jquery.each() to iterate over each .wrapper:

var divs = [];
$('div.wrapper').each(function() {
   var $this = $(this);
   divs.push({
       divinfo: {
           title: $this.find('h3').html(),
           description: $this.find('p').html()
       }
   });
});

Comments

0

sure, just an example...

var divArr = document.getElementsByTagName('DIV');

for (var i= 0; i < divArr.length; i++) {
  if (divArr[i].className !== 'container') {
    divArr[i].title = 'new title';
  }
}

1 Comment

tell me m0re, i'll help you 0ut.
-1

If you're trying to create the HTML elements based on your array of information, you can use code like this:

// get the container element in which you want to insert divs
var container = document.querySelector(".container");

// loop through all the elements in your array
for(var i = 0, len = div.divInfo.length; i < len; i++){
    // create the actual div element to insert
    var wrapper = document.createElement("div");
    // specify element attributes here as necessary
    // append the element to the container
    container.appendChild(wrapper);
}

Here's some working example code:

var div = {
    divInfo: [
      {
        title: "title",
        description: "Lorem ipsum dolor sit amet, consectetur adipiscing"
      },
      {
        title: "another title",
        description: "Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus."
      }
    ]
  };
var container = document.querySelector(".container");
for(var i = 0, len = div.divInfo.length; i < len; i++){
  var wrapper = document.createElement("div");
  wrapper.className = "wrapper";
  wrapper.style.backgroundColor = "#dfdfdf;"; 
  var header = document.createElement("h3");
  header.innerHTML = div.divInfo[i].title;
  var body = document.createElement("p");
  body.innerHTML = div.divInfo[i].description;
  wrapper.appendChild(header);
  wrapper.appendChild(body);
  container.appendChild(wrapper);
}
<div class="container"></div>

If you're trying to create an array based on existing HTML elements on the page, you can use code like this:

// grab all the divs with the wrapper class, inside the element with the container class
var divs = document.querySelectorAll(".container div.wrapper");
// loop through the results
for(var i = 0, len = divs.length; i < len; i++){
    var currentDiv = divs[i];
    // modify the elements or extract data from them here
}

Again, here's some working example code:

var divs = document.querySelectorAll(".container div.wrapper");
var div = {divInfo:[]};
for(var i = 0, len = divs.length; i < len; i++){
  var currentDiv = divs[i];
  var title = divs[i].querySelector("h3").innerHTML;
  var description = divs[i].querySelector("p").innerHTML;
  div.divInfo.push({title:title, description:description});
  currentDiv.style.backgroundColor = "#dfdfdf";
}
document.getElementById("output").innerHTML = "div = "+JSON.stringify(div);
<div class="container">
   <div class="wrapper">
      <h3>Title</h3>
      <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit</p>
   </div>
     <div class="wrapper">
      <h3>Another Title</h3>
      <p>Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus.</p>
   </div>
</div>
<hr/>
<b>Code Result:</b>
<div id="output"></div>

Both of those examples update the background of the divs using element.style.backgroundColor.

Comments

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.