javascripthtml

add rows to table dynamically and make content editable


I need to add rows to a table, I have manually added the header row, and make the content editable by the user.

Currently I have:

const table = document.getElementById("tableData");

for (let i = 0, add = 5; i < add; i++) {
  const row = table.insertRow(0);
  const cell1 = row.insertCell(0);
  const cell2 = row.insertCell(1);
  cell1.textContent = "New";
  cell2.textContent = "New";
}

which i have used just to practice adding in rows. I've seen that to make a cell editable you need to put a div inside with "contenteditable". How can I add this into the code that I already have?


Solution

  • There is one thing you should note:

    <td> elements (among some others) cannot be set to contenteditable directly in IE: See http://msdn.microsoft.com/en-us/library/ms537837(v=vs.85).aspx

    For completeness, there are several ways to do this

    var table = document.getElementById("tableData");
    
        var add = 5;
    
        for (var i = 0; i < add; i++) {
    
            var row = table.insertRow(0);
    
            var cell1 = row.insertCell(0);
    
            // Method 1 (Restricted in IE)
            cell1.innerHTML = "Method 1";
            cell1.setAttribute('contentEditable', 'true');
    
            // Method 2 (Restricted in IE)
            cell1.innerHTML = "Method 2";
            cell1.contentEditable = true;
    
            // Method 3 (All browsers)
            cell1.innerHTML = "<div contenteditable>Method 3</div>";
    
            // Method 4 (All browsers)
            var div1 = document.createElement('div');
            div1.innerHTML = "Method 4";
            cell1.appendChild(div1);
            div1.contentEditable = true;
        }