JavaScript INDEX_SIZE_ERR: DOM exception 1

In the following code, I get the indicated error and am not quite sure why. I looked at other topics here, but didn't seem to find an error.

The purpose of the script is to store arrays of strings in localstorage. These string arrays are then loaded into the table.

The following function gets the values ​​from the fields of my web form: -

function saveContact() { var contact = [nameDOM.value, addDOM.value, townDOM.value, postalDOM.value, mobDOM.value]; localStorage.setItem(window.localStorage.length, contact); showContacts(); } 

This function places this information in a table: -

  function showContacts() { for(i=0; i<window.localStorage.length; i++) { var contactRow = cTableDOM.insertRow(i); var contactCell = contactRow.insertCell(i); var text = document.createTextNode(localStorage.getItem(i)); contactCell.appendChild(text); } } 

The behavior I get is this; when I try to enter different “contacts” into my desk, the first “contact” is repeated instead of the last “contacts”.

+4
source share
1 answer

The problem is that you create a new line and call insertCell(2) . Since this is more than the number you get INDEX_SIZE_ERR.

From Mozilla (highlighted by me):

If the index is -1 or equal to the number of cells, the cell is added as the last cell in the row. If the index is omitted or greater than the number of rows, this will result in an error.

You can also just call appendChild for the newly created td .

 var contactCell = contactRow.appendChild(document.createElement("td")); 
+3
source

Source: https://habr.com/ru/post/1392349/


All Articles