3

Why pictures don't appear on my page? Uncaught IndexSizeError: Failed to execute 'insertCell' on 'HTMLTableRowElement': The value provided (1) is outside the range [-1, 0] - this error call on this string.

[JS]var cell = row.insertCell(i);[/JS]




function createPreview() {
var f = document.createElement("table");
var row = f.insertRow();
var cell = row.insertCell(i);

for(var j = 0; j < count ; j++) {
var img = new Image();
img.src = "image/" + j + ".jpg";
img.id = "i" + j;
cell.appendChild(img);
}

document.body.appendChild(f);

}
</script>[/JS]
cat
  • 31
  • 1
  • 3

3 Answers3

7

This is old, but for anyone reaching here, and having the same problem, the first cell you have to put in a row is the cell 0, then, you can put the cell 1, for example: You cant put the cell 0, and after that the cell 2, because you need a cell 1.

The way to do it is insert cell 0,1,2,3...

Gaunt
  • 649
  • 8
  • 20
1

Just to add to Gaunts answer, cause this one came up for me too.

I was creating a new tbody, and within this tbody I was dynamically creating new rows by looping through an array.

Initially, I had the code loop using the typical for loop which was working fine.

var tableBody = tableBody || document.createElement('tbody')

for (var i = 0, rowCtr = rowOrder.length; i < rowCtr; i++) {
    var newRow = tableBody.insertRow(i);
}

But then I went ahead and refactored to use a reverse for loop to reduce the verbosity of that for statement and for the performance advantages at no extra cost to readability and future maintenance.

var tableBody = tableBody || document.createElement('tbody')

for (var i = rowOrder.length; i--;) {
    var newRow = tableBody.insertRow(i);
}

Both for loops have the same expected result, with the reverse for loop being more readable. So if rowOrder is an array of 4 elements, using the reverse for loop will yield this:

start loop
i = 3
i = 2
i = 1
i = 0
end loop

In this loop, the first run through will attempt var newRow = tableBody.insertRow(3) so you will get an index error because a row at position 0, 1, 2 have not been previously created.

This happened to me on Google Chrome 46.0.2490.80 m - not sure why they thought to throw exceptions on creating a sparse array of rows in the tbody, they can just restructure their code to allow for sparse arrays and then prior to updating the DOM, just re-sort the index keys. Even that is unnecessary, just push the rows out.

puiu
  • 726
  • 9
  • 18
0

Just bumped into this, so I guessing the error is trying to tell you that you can only add to the front; (0) or at the back; (-1)

found this link , Hope it helps

for(i=0;i<names.length;i++){
    if(i===0){
        var cell=column.insertCell(0);;
        cell.outerHTML = "<th>Heading</th>";
    }else{
        var cell=column.insertCell(-1);
        cell.outerHTML = "<input>";
    }
}
Lakshya Raj
  • 1,669
  • 3
  • 10
  • 34
Kimutai
  • 71
  • 4