Array elements not showing up in dynamically created divs?
im trying to print array elements with html element li
in dynamically generated div
but no errors show and neither array elements are just empty div
.
What could be wrong?
Here is my code:
var fruitsName, fruitsLists, numFruits, i;
fruitsName = ["Mango", "Apple", "Banana", "Strawberry", "Blackberry", "Blueberry"];
numFruits = fruitsName.length;
fruitsLists = "<ul>";
for (i = 0; i < numFruits.length; i++)
{
fruitsLists = "<li>" + fruitsName[i] + "</li>";
}
fruitsLists += "</ul>";
var myDiv = document.createElement('div');
myDiv.className = 'bookmarksHolder';
myDiv.id = 'randomItem';
document.getElementById('bookmarks_row').appendChild(myDiv);
document.getElementById('randomItem').innerHTML = fruitsLists;
source to share
Two problems: numFruits
already the length of the array, so it should be simple i < numFruits
. Second, in a loop, concatenate the previous value with the current one:
for (i = 0; i < numFruits; i++) {
fruitsLists += "<li>" + fruitsName[i] + "</li>";
}
Complete sample:
var fruitsName, fruitsLists, numFruits, i;
fruitsName = ["Mango", "Apple", "Banana", "Strawberry", "Blackberry", "Blueberry"];
numFruits = fruitsName.length;
fruitsLists = "<ul>";
for (i = 0; i < numFruits; i++) {
fruitsLists += "<li>" + fruitsName[i] + "</li>";
}
fruitsLists += "</ul>";
var myDiv = document.createElement('div');
myDiv.className = 'bookmarksHolder';
myDiv.id = 'randomItem';
document.getElementById('bookmarks_row').appendChild(myDiv);
document.getElementById('randomItem').innerHTML = fruitsLists;
<div id="bookmarks_row"></div>
source to share
You are assigning fruitsLists
in a loop instead of adding. Also the length of your array numFruits
, so don't call .length
. Change your loop to:
for (i = 0; i < numFruits; i++)
{
fruitsLists += "<li>" + fruitsName[i] + "</li>";
}
You can also pass ul
as innerHTML in div
before being attached div
to the DOM. This will only call the render engine once, not twice, and you won't need to find div
by ID:
var myDiv = document.createElement('div');
myDiv.className = 'bookmarksHolder';
myDiv.id = 'randomItem';
myDiv.innerHTML = fruitsLists;
document.getElementById('bookmarks_row').appendChild(myDiv);
source to share
Inside the loop, you need to concatenate, not update the integer values, otherwise fruitsLists
includes the last generated HTML li. While updating the loop condition because it numFruits
contains the length.
for (i = 0; i < numFruits; i++)
// ---------^^^---
{
fruitsLists += "<li>" + fruitsName[i] + "</li>";
// ---^^^---
}
source to share