Search code examples
jqueryhtml-tablehtml-content-extraction

How to get the value of a row extracted using jQuery


I have a table and I'm retrieving each table row by doing this:

$(function(){
        $('table tr').click(function(){
            var $row = $(this).html();
            alert($row);
        });
    });

This gets me the current row like this:

<td>2</td>
<td>Malcriado</td>
<td>Bota</td>
<td>Tipo2</td>
<td>NuevaDesc</td>
<td>NuevaDesc</td>
<td></td>
<td>Cerdo</td>
<td>Azul</td>
<td>oso</td>
<td>Rojo</td>
<td>12</td>
<td>metal</td>
<td>sss</td>
<td></td>
<td>Delicias</td>

What I am trying to accomplish next is to remove the td's and get the values in between and get them into an array, but I haven't been able to accomplish this. Any ideas?


Solution

  • Use the children()(docs) method to get the <td> elements, then the map()(docs) method to create an Object containing the values, and finally the toArray()(docs) method to convert it into an Array.

    $('table tr').click(function(){
        var values = $(this).children('td').map(function() {
            return this.innerHTML;
        }).toArray();
    
        alert(values);
    });