JSFiddle - React, Tailwind, and code Playground
by Alexis López Espinoza
HTML
<table id="lista">
<thead>
<tr>
<th>Celda 1</th>
<th>Celda 2</th>
<th>Celda 3</th>
<th>Opciones</th>
</tr>
</thead>
<tbody>
<tr>
<td>Dato 1</td>
<td>Dato 2</td>
<td>Dato 3</td>
<td>
<span class="delete">Eliminar</span>
</td>
</tr>
<tr>
<td>Dato 1</td>
<td>Dato 2</td>
<td>Dato 3</td>
<td>
<span class="delete">Eliminar</span>
</td>
</tr>
<tr>
<td>Dato 1</td>
<td>Dato 2</td>
<td>Dato 3</td>
<td>
<span class="delete">Eliminar</span>
<span class="add">Agregar</span>
</td>
</tr>
</tbody>
</table>
CSS
html, body{
width: 100%;
height: 100%;
}
#lista{
border-collapse: collapse;
text-align: center;
width: 90%;
}
#lista thead tr th:first-child,
#lista tbody tr td:first-child{
border-left: .1rem black solid;
}
#lista thead tr th, #lista tbody tr td{
border-right: .1rem black solid;
border-bottom: .1rem black solid;
padding: 2.5%;
}
#lista thead tr th{
border-top: .1rem black solid;
}
#lista thead tr{
background-color: chocolate;
color: white;
}
#lista span{
cursor: pointer;
border: .1rem black solid;
padding: 2.5% 5%;
color: white;
font-weight: bold;
}
#lista span:hover{
filter: brightness(1.2);
-webkit-filter: brightness(1.2);
-moz-filter: brightness(1.2);
-o-filter: brightness(1.2);
}
.delete{
background-color: red;
}
.add{
background-color: green;
}
JavaScript
var tbody = document.querySelector("#lista tbody"),
boton, celda, fila, clon;
tbody.addEventListener("click", function(event){
boton = event.target;
celda = boton.parentNode;
fila = celda.parentNode;
if (boton.className == "add"){
clon = fila.cloneNode(true);
celda.removeChild(boton);
this.appendChild(clon);
}
if (boton.className == "delete"){
if (tbody.querySelectorAll("tr").length > 1){
if(confirm("¿Estás seguro de querer eliminar esta fila?")){
if (boton.nextElementSibling){
clon = boton.nextElementSibling.cloneNode(true);
fila.previousElementSibling.querySelector("td:last-child").appendChild(clon);
}
this.removeChild(fila);
}
}
else{
alert("No puedes eliminar más filas");
}
}
}, false);