I was practicing something simple in jquery, in this case adding new rows to a table through a button, for which I have two pieces of code:
The first one using the selector tbody:last-child
and the function append()
of jquery.
$("#add").on("click", function(){
$('#test > tbody:last-child').append('<tr><td>'+$("#nombre").val()+'</td><td>'+$("#apellido").val()+'</td></tr>');
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Test Tabla</title>
</head>
<body>
Nombre: <input type="text" id="nombre">
Apellido: <input type="text" id="apellido">
<button type="button" id="add">Agregar</button>
<table id="test">
<thead>
<tr>
<th>Nombre</th>
<th>Apellido</th>
</tr>
</thead>
<tbody>
<tr>
<td>
Luis
</td>
<td>
Paredes
</td>
</tr>
</tbody>
</table>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>
And the second one using the selector tr:last
and the function after()
$("#add").on("click", function(){
$('#test tr:last').after('<tr><td>'+$("#nombre").val()+'</td><td>'+$("#apellido").val()+'</td></tr>');
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
Nombre: <input type="text" id="nombre">
Apellido: <input type="text" id="apellido">
<button type="button" id="add">Agregar</button>
<table id="test">
<thead>
<tr>
<th>Nombre</th>
<th>Apellido</th>
</tr>
</thead>
<tbody>
<tr>
<td>
Luis
</td>
<td>
Paredes
</td>
</tr>
</tbody>
</table>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>
My question is:
Is there any other way to do it, and which of the two ways is better implemented?