Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create divs from Array elements

I have different strings in my array. Is it possible to create a divs like <div id="results"></div> for each array element in my HTML page?

like image 942
mike643 Avatar asked May 04 '11 15:05

mike643


3 Answers

Sure, simple example without using any frameworks or libraries:

var cars = 'Saab,Volvo,BMW,GMC,Nissan,Ford'.split(',');
for (var c in cars) {
    var newElement = document.createElement('div');
    newElement.id = cars[c]; newElement.className = "car";
    newElement.innerHTML = cars[c];
    document.body.appendChild(newElement);
} 

You can take a look at how this works using jsFiddle here: http://jsfiddle.net/Shaz/geNNa/

like image 122
Shaz Avatar answered Oct 31 '22 08:10

Shaz


Yeah, using a for loop:

var arrayVariable = ['one','two','three'],
    arrayLength = arrayVariable.length;

for (i = 0; i < arrayLength; i++) {
  $('<div class="results" />').text(arrayVariable[i]).appendTo('body');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Or slightly more jQuery-fied:

var arrayVariable = ['one', 'two', 'three'];

$.each(arrayVariable, function(index, value) {
  $('<div />', {
    'text': value
  }).appendTo('body');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You could do this in vanilla JavaScript too, if you'd prefer:

var arrayVariable = ["one", "two", "three"];
var arrayLength = arrayVariable.length;
var temp;

for (i = 0; i < arrayLength; i++) {
  temp = document.createElement('div');
  temp.className = 'results';
  temp.innerHTML = arrayVariable[i];
  document.getElementsByTagName('body')[0].appendChild(temp);
}

It's worth considering where the id is coming from; if more than one element is to be produced by this for loop, it might be better (depending on where, and how, the id is assigned) to use a class instead, as I did in both of my suggestions, as the id must be unique within the document.

While this answer was written quite a while ago, I felt it worth updating to reflect the possibilities offered by the (relatively new) Array.prototype.forEach(), which iterates over each element of a given array, and applies a function for each iteration. For example, given the HTML:

<ul id="fruits"></ul>

And the JavaScript:

var fruitsList = document.getElementById('fruits'),
    li = document.createElement('li'),
    clone;
['apples','bananas','cranberries'].forEach(function (fruit, index) {
    clone = li.cloneNode();
    clone.textContent = index + ': ' + fruit;
    fruitsList.appendChild(clone);
});

Resulting in the output:

<ul id="fruits">
    <li>0: apples</li>
    <li>1: bananas</li>
    <li>2: cranberries</li>
</ul>

var fruitsList = document.getElementById('fruits'),
  li = document.createElement('li'),
  clone;
['apples', 'bananas', 'cranberries'].forEach(function(fruit, index) {
  clone = li.cloneNode();
  clone.textContent = index + ': ' + fruit;
  fruitsList.appendChild(clone);
});
<ul id="fruits"></ul>

References:

  • JavaScript:
    • Array.prototype.forEach().
    • document.createElement().
    • document.getElementById().
    • document.getElementsByTagName().
    • Element.className.
    • Element.innerHTML.
    • Node.appendChild().
    • Node.cloneNode().
    • Node.textContent.
  • jQuery:
    • appendTo().
    • $.each().
    • text().
like image 45
David Thomas Avatar answered Oct 31 '22 09:10

David Thomas


A Basic For Loop + jQuery should do it. Just replace body with a selector for the container you want to add the divs to. Here is a fiddle showing the technique in use.

var myCars=new Array("Saab","Volvo","BMW");

for(var x=0; x<myCars.length; x++){
    $('body').append('<div id="' + myCars[x] + '">' + myCars[x] + '</div>');
}
like image 3
Dutchie432 Avatar answered Oct 31 '22 08:10

Dutchie432