Stephen Gevanni Stephen Gevanni - 1 month ago 11
Javascript Question

Put each element of an array, in a cell of a table created by Javascript

I've created a table using javascript. However, I would like each of the cells (

td
) in the table to display each element in my array, in order of the elements in the array.
This is the array with the words in it:

var Myarray=['Anime','Demon','Black','Death','Beast','Tokyo','Manga','Titan','Ghoul'];


Here is my Javascript code so far:

function display_array(Myarray){
var body = document.body,
tbl = document.createElement('table');
tbl.style.width = '100px';
tbl.style.border = "1px solid black";
var arrayLength = Myarray.length;
var sqroot=Math.sqrt(arrayLength);

for(var i = 0; i < sqroot; i++){
var tr = tbl.insertRow();
for(var j = 0; j < sqroot; j++){
if(i == sqroot && j == sqroot){
break;
} else {
var td = tr.insertCell();


for(var q = 0; q < arrayLength; q++){
td.appendChild(document.createTextNode(Myarray[q]));
}

td.style.border = "1px solid black";
if(i == 1 && j == 1){
td.setAttribute('rowSpan', '1');
}
}
}
}
body.appendChild(tbl);

}


With this code, my table looks like this:

____________________________________________________________________________________________________________________________________________
|AnimeDemonBlackDeathBeastTokyoMangaTitanGhoul|AnimeDemonBlackDeathBeastTokyoMangaTitanGhoul|AnimeDemonBlackDeathBeastTokyoMangaTitanGhoul|
--------------------------------------------------------------------------------------------------------------------------------------------
|AnimeDemonBlackDeathBeastTokyoMangaTitanGhoul|AnimeDemonBlackDeathBeastTokyoMangaTitanGhoul|AnimeDemonBlackDeathBeastTokyoMangaTitanGhoul|
--------------------------------------------------------------------------------------------------------------------------------------------
|AnimeDemonBlackDeathBeastTokyoMangaTitanGhoul|AnimeDemonBlackDeathBeastTokyoMangaTitanGhoul|AnimeDemonBlackDeathBeastTokyoMangaTitanGhoul|
--------------------------------------------------------------------------------------------------------------------------------------------


I would like my table to look like this:

___________________
|Anime|Demon|Black|
-------------------
|Death|Beast|Tokyo|
-------------------
|Manga|Titan|Ghoul|
-------------------

Answer
for(var q = 0; q < arrayLength; q++){
    td.appendChild(document.createTextNode(Myarray[q]))
}

This loops thru and create a textNode for each element. If you want one element use Myarray[index]; in this case index is i * sqroot + j.

td.appendChild(document.createTextNode(Myarray[i * sqroot + j]))
Comments