Get value from row th on a table with jquery

1

Good afternoon I have the following question, suppose I have the following table

<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
    border: 1px solid black;
}
</style>
</head>
<body>

<table>
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
  </tr>
</table>

</body>
</html>

How do I get the name of the column (Month or Savings) with jquery?

Thank you very much

    
asked by Alexander J. Marcano 08.03.2018 в 21:06
source

2 answers

2

Quite simple, as if you had to apply styles to those same elements of the DOM.

// Aplico un ciclo para recorrer todos los elementos del tag th
$('table tr:first th').each(function() {
  // Obtengo el valor de dicho th
  var value = $(this).text();
  // Acá deberías hacer lo que quieras con ese valor obtenido
  alert(value);
});
    
answered by 08.03.2018 / 21:20
source
0

Good to see if I understood you, just add ids, select them and get their value.

<!DOCTYPE html>
<html>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<head>
    <style>
        table,
        th,
        td {
            border: 1px solid black;
        }
    </style>
</head>

<body>

    <table>
        <tr>
            <th id="column1">Month</th>
            <th id="column2">Savings</th>
        </tr>
        <tr>
            <td>January</td>
            <td>$100</td>
        </tr>
        <tr>
            <td>February</td>
            <td>$80</td>
        </tr>
    </table>

</body>
<script>    
    var $column1 = $("#column1").text();
    console.log("column1: " + $column1);
    var $column2 = $("#column2").text();
    console.log("column2: " + $column2);
</script>

</html>
    
answered by 08.03.2018 в 21:22