add editable html row with javascript and HTML only
As others noted the cells variables are <td>
elements already. You can just set the contentEditable
property to true.
Also I would change the mouseup
event to a click
event. The mouseup
event is not triggered in keyboard inputs. However if you want to use the mouseup
for some reason you can still do it.
document.getElementById("addRow").addEventListener("click", function() {
var table = document.getElementById("table")
var row = table.insertRow(0);
var cell0 = row.insertCell(0);
cell0.contentEditable = true;
cell0.textContent = 'Property';
var cell1 = row.insertCell(1);
cell1.contentEditable = true;
cell1.textContent = 'Value'
})
table,
th,
td {
border: 1px solid black;
}
<div id="wrapper">
<button id="addRow">+</button>
<button id="deleteRow">-</button>
<table id="table">
<tbody>
<!-- filled by script -->
</tbody>
</table>
</div>
The problem isn't contenteditable
, the problem is that the code is trying to append a <td>
element immediately within a <td>
element. cell0
and cell1
already are <td>
elements. The browser is "correcting" the markup and removing the invalid inner <td>
, leaving you with just a table with text in it.
Change those inner <td>
elements to something like a <div>
instead:
cell0.innerHTML = '<div contenteditable="true">Property</div>';
cell1.innerHTML = '<div contenteditable="true">Value</div>'