Estoy creando una tabla html que comienza solo con una fila de encabezado y el usuario tiene un botón Agregar nueva fila que agrega filas a la tabla. Logré que eso funcione, pero necesito que el usuario pueda editar la nueva fila. Intenté usar contenteditable=“true”, pero solo puedo hacerlo si las filas ya se crearon en el archivo html. ¿Cómo hago que mi función javascript que crea las nuevas celdas incluya la propiedad contenteditable?
Puede establecer el atributo de un elemento después de crearlo y antes de agregarlo al 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>