I was practicing something simple in jquery, in this case adding new rows to a table via a button, for which I have two code snippets:
The first using the jquery selector tbody:last-child
and function .append()
$("#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 using the selector tr:last
and the functionafter()
$("#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?
Yes, there are many other ways to do it, the truth and with all due respect, I think as many as we can imagine and create. On English SO there is a question that offers over 20 different options to do this.
Which of the two is better implemented? I think there is no major difference, they are simply two different ways to solve the problem.
In terms of the source code of the methods used, the difference between one and the other should be minimal in terms of performance:
Finally, regarding the implementation that you do, the selectors could be slightly improved, in the first case it is not necessary to specify
:last-child
and in the second we could avoid the use of the descendant selector and addtbody
, if there is one<tfoot>
at the end of the table.Adding to @Shaz's excellent answer:
If you mean implementation in general terms, none. Avoid using that kind of non-reusable code, instead you can use functions for it that serve as templates. For example, your code can be modularized like this:
Regarding performance between
jQuery#append
andjQuery#after
, there are no notable differences.