Add row to an html table

3

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?

    
asked by Juan Pinzón 28.09.2016 в 17:31
source

2 answers

5

Yes, there are many other ways of doing it, the truth and with all due respect I think that as many as we can imagine and create. In SO in English there is a question that offers more than 20 different options to do this.

Which of the two is better implemented? I think there is no greater difference, they are simply two different ways of solving 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:

append: function() {
    return domManip( this, arguments, function( elem ) {
        if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
            var target = manipulationTarget( this, elem );
            target.appendChild( elem );
        }
    } );
},


after: function() {
    return domManip( this, arguments, function( elem ) {
        if ( this.parentNode ) {
            this.parentNode.insertBefore( elem, this.nextSibling );
        }
    } );
},

Finally, regarding the implementation 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 add tbody , in if there is <tfoot> at the end of the table.

$("#add").on("click", function(){
  $('#test > tbody').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>

$("#add").on("click", function(){
  $('#test > tbody > 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>
    
answered by 28.09.2016 / 18:32
source
2

Adding to the excellent response of @Shaz:

  

Which of the two is better implemented?

If you mean implementation in general terms, none. Avoid using that type of non-reusable code, instead you can use functions that serve as templates. For example, your code can be modularized like this:

function addPerson(e) {
  e.preventDefault();
  const row = createRow({
    name: $('#name').val(),
    lastname: $('#lastname').val()
  });
  $('table tbody').append(row);
  clean();
}

function createRow(data) {
  return (
    '<tr>' +
      '<td>${$('tbody tr').length + 1}</td>' +
      '<td>${data.name}</td>' +
      '<td>${data.lastname}</td>' +
    '</tr>'
  );
}

function clean() {
  $('#name').val('');
  $('#lastname').val('');
  $('#name').focus();
}
*,
*:before,
*:after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
body {
  padding: 1rem;
  text-align: center;
}
form {
  display: inline-flex;
}
form input {
  border: 1px solid #ccc;
  color: #333;
  font-family: 'segoe ui';
  font-size: 14px;
  outline: none;
  padding: .4rem .8rem;
}
form button {
  background-color: #1abc9c;
  border: 1px solid #1abc9c;
  color: rgba(255,255,255,.93);
  font-family: 'segoe ui';
  margin-left: 10px;
  padding: .4rem 1rem;
  transition: background-color .2s ease,
    color .2s ease;
}
form button:hover {
  background-color: #ffF;
  color: #1abc9c;
}
table {
  border-collapse: collapse;
  border: 1px solid #ccc;
  margin-top: 25px;
}
table thead th {
  background-color: #f2f2f2;
  font-weight: 500;
}
table thead th,
table tbody td {
  color: #333;
  font-family: 'segoe ui';
  font-size: 14px;
  padding: .5rem .65rem;
}
table thead th:not(:last-of-type),
table tbody td:not(:last-of-type) {
  border-right: 1px solid #ccc;
}
table thead tr,
table tbody tr:not(:last-of-type) {
  border-bottom: 1px solid #ccc;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>

  <form onsubmit="addPerson(event)">
    <section class="group">
      <input type="text" id="name" placeholder="Nombre" />
      <input type="text" id="lastname" placeholder="Apellido" />
    </section>
    <button type="submit">Agregar</button>
  </form>
  
  <table style="display: inline-block">
    <thead>
      <tr>
        <th>#</th>
        <th>Nombre</th>
        <th>Apellido</th>
      </tr>
    </thead>
    <tbody>
      
    </tbody>
  </table>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>

On performance between jQuery#append and jQuery#after , there are no noticeable differences.

    
answered by 28.09.2016 в 18:47