The first problem I see is that i
and i % 4
is not the images in your table, it's the images in the returned data. The two will differ as soon as you encounter an image already in your array. You need to use an index for the i % 4
that is the actual number of images in the table. You could use a separate count of how many images are in the table that you intialize with:
var imageCnt = document.getElementById("images").getElementsByTagName("td").length
And, the increment that any time you add an image to the table and then check %imageCnt % 4
to decide when to add a new row.
Then, don't you want to be adding images to the LAST row in the table, not the first row in the table because that's where the extra slots will be and where the new empty row goes. You will be adding images to the last row when you've just created a new row, but not when your last row is partially filled when you start. In that case, you'll be adding images to the first row. You can start with the last row
var table = document.getElementById("images");
var lastRow = table.rows[table.rows.length - 1];
Applying these to your first example of code would work like this:
//...
//unneccessary
//...
var album_photos = JSON.parse(xhr2.responseText);
var table = document.getElementById("images");
var tableBody = table.getElementsByTagName("tbody")[0];
var lastRow = table.rows[table.rows.length - 1];
// initialize cell count
var cellCount = table.getElementsByTagName("td").length;
for(var i = 0; i < album_photos.length; i++) {
if(!isInArray(album_photos[i].Image_ID, image_ids)) {
if (cellCount % 4 == 0 && cellCount !== 0) {
// make new row and append it to the table body
lastRow = document.createElement("tr");
tableBody.appendChild(lastRow);
}
//...
//creating elements to be append
//...
td.appendChild(imagewrap);
imagewrap.appendChild(imagemenu);
imagemenu.appendChild(imagemenuimg1);
imagemenu.appendChild(imagemenuimg2);
imagewrap.appendChild(imagewrapimg);
// best to append the new cell when it's fully formed
lastRow.appendChild(td);
++cellCount;
image_ids.push(album_photos[i].Image_ID);
//...![enter image description here][1]
//unneccessary