im creating an html table that starts with only a header row and the user has an add new row button that adds rows to the table. Ive managed to get that to work but I need the new row to be editable by the user. I tried using contenteditable=“true” but i can only do that if the rows were already created in the html file. How do i make my javascript function that creates the new cells include the contenteditable property?
You can set the attribute of an element after you created it & before you actually add it to the DOM.
const getCellEditable = () => {
const cell = document.createElement("td")
cell.setAttribute("contenteditable", true)
return cell
}
const getRow = () => {
const row = document.createElement("tr")
row.append(getCellEditable())
row.append(getCellEditable())
return row
}
const tbody = document.getElementById("tbody")
const btnAddRow = document.getElementById("add-row")
const addRow = (parent) => {
parent.append(getRow())
}
btnAddRow.addEventListener("click", function() {
addRow(tbody)
})
tr,
th,
td {
border: 1px solid black;
}
#table {
border-collapse: collapse;
}
th,
td {
padding: 8px 16px;
}
<button id="add-row">ADD ROW +</button>
<br />
<br />
<table id="table">
<thead>
<tr>
<th>
First
</th>
<th>
Second
</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>