I have different strings in my array. Is it possible to create a divs like
for each array element in my HTML page?
Yeah, using a for loop:
var arrayVariable = ['one','two','three'],
arrayLength = arrayVariable.length;
for (i = 0; i < arrayLength; i++) {
$('').text(arrayVariable[i]).appendTo('body');
}
Or slightly more jQuery-fied:
var arrayVariable = ['one', 'two', 'three'];
$.each(arrayVariable, function(index, value) {
$('', {
'text': value
}).appendTo('body');
});
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:
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:
- 0: apples
- 1: bananas
- 2: cranberries
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);
});
References: