M56035G M56035G - 3 months ago 9
Javascript Question

How to get the cells header name of cells to whom am passing a different class name in table

Here what am trying to get the cell header name of those cells who has a specific class assigned like suppose i have 10 cells in each row and some of them has class by name like test,then i want to store the names of all those cells in array who has this class name

my HTML as like bellow


<table>
<tr>
<th>Header1</th>
<th>Header2</th>
<th>Header3</th>
</tr>
<tr>
<td class="test">gggg</td>
<td>hhhh</td>
<td class="test">iiiiiii</td>
</tr>
<tr>
<td>ddddd</td>
<td>eeee</td>
<td>ffffff</td>
</tr>
</table>




as per above HTML thesr should be a Header1 and Header3 in array,here i want to get this data without click event,means am adding the class name to these cells using javascript means that is dynamic so i want to store the name of the header cells in array whenever cells under that header cell will have this class and this class assignment is happening for single row only in entire table

Answer

Since your table is regular (no colspans), it's quite straightforward:

  • Find the index of the cells with the class test using index.

  • Find the matching header cells using the :eq pseudo-selector (.e.g, $("selector-for-the-table th:eq(" + index + ")") where index is the index of the header cell you want). (Or the .eq function could be used in a similar way.)

  • Get the th's text using text.

Example:

var indexes = $(".test").map(function() {
  return $(this).index();
}).get();
var headers = indexes.map(function(index) {
  return $("th:eq(" + index + ")").text();
});
console.log(headers);

var indexes = $(".test").map(function() {
  return $(this).index();
}).get();
var headers = indexes.map(function(index) {
  return $("th:eq(" + index + ")").text();
});
console.log(headers);
<table>
  <tr>
    <th>Header1</th>
    <th>Header2</th>
    <th>Header3</th>
  </tr>
  <tr>
    <td class="test">gggg</td>
    <td>hhhh</td>
    <td class="test">iiiiiii</td>
  </tr> 
  <tr>
    <td>ddddd</td>
    <td>eeee</td>
    <td>ffffff</td>
  </tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Or more compactly:

var headers = $(".test").map(function() {
  return $("th:eq(" + $(this).index() + ")").text();
}).get();
console.log(headers);

var headers = $(".test").map(function() {
  return $("th:eq(" + $(this).index() + ")").text();
}).get();
console.log(headers);
<table>
  <tr>
    <th>Header1</th>
    <th>Header2</th>
    <th>Header3</th>
  </tr>
  <tr>
    <td class="test">gggg</td>
    <td>hhhh</td>
    <td class="test">iiiiiii</td>
  </tr> 
  <tr>
    <td>ddddd</td>
    <td>eeee</td>
    <td>ffffff</td>
  </tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>