Tess Tess - 5 months ago 8
Javascript Question

Match two arrays with condition

I have table without td/th-id's/classes and I loop through the table to get the data from the td:s. If there is no data or data is: "-" then I set a CSS-class on that td. Like this:

$('.simpletable td').each(function() {
if($(this).text() === '-')
{
$(this).addClass("nodata");
}
});


However I need to match that 'td' with the corresponding 'th' to set the same CSS-class. I fetch an array for the th-array with:

$('.simpletable th').each(function()
{
tableheaders.push($(this).text());
});


Does anyone know how to achieve this? Or is there a simpler way to do all of this this if I start from scratch?

This table has several rows of 'th' so I cant really do anything with columns.

MARKUP html:

<table class="simpletable">
<thead>
<th>th1</th>
<th>th2</th>
<th>th3</th>
</thead>
<tbody>
<tr>
<td>data 1</td>
<td>-</td>
<td>data 3</td>
</tr>
<thead>
<th>th4</th>
<th>th5</th>
<th>th6</th>
</thead>
<tr>
<td>data 4 row 2</td>
<td>-</td>
<td>data 6 row 2</td>
</tr>
</tbody>



Answer

You have to capture the index of the td then use .filter() to get the appropriate th that have the same column index

$('.simpletable td').each(function() {
 if($(this).text() === '-')
  {
    $(this).addClass("nodata");
    var ind = $(this).index(); // get td index relative to it's row
    $('.simpletable th').filter(function(i,v){
        return $(v).index() == ind; // only return th with same column index as the td
    }).addClass('nodata');
  }
});