How to highlight an HTML table column without using loops?

Issue

I have a table like this:

<table>
  <thead>
    <tr>
     <th id="col-1"><input type="button" class="some" value="Company" /></th>
     <th>name</th>
     <th>Adress</th>
     <th>Zip</th>
     <th>Place</th>
     <th>Country</th>
    </tr>
   </thead>
   <tbody>
    <tr class="even">
     <td headers="col-1">Some ltd</td>
     <td>some name</td>
     <td>some street</td>
     <td>some zip</td>
     <td>some town</td>
     <td>some country</td>
    </tr>
    <tr class="odd">
     <td headers="col-1">Corp</td>
     <td>some name</td>
     <td>some street</td>
     <td>some zip</td>
     <td>some town</td>
     <td>some country</td>
    </tr>
   </tbody>
 </table>

Odd and even rows have different highlight classes oddHigh and evenHigh.

On click of the column header I want to highlight the column like this:

$(".some").live("click", function() {
   var val = $(this).closest("TH, th").attr('id'),
       col = $( "td[headers="+ val +"]" ),
       // set odd/even
       i = col.closest("TR, tr").hasClass("odd") ? "oddHigh" : "evenHigh";

   col.hasClass("colHigh") ? col.removeClass("colHigh "+i) : col.addClass("colHigh "+i);
   });

This highlights the whole column with oddHigh.

Is there a way to highlight depending on the class of the closest row WITHOUT looping through the whole selection? Or do I need to set colOdd to tr.odd td… and colEven to tr.even td.. and use 2 separate statements?

Solution

You can use the css :even and :odd css pseudo-class selectors if your browser supports them. also

tr:nth-child(odd)

and

tr:nth-child(even)

see http://caniuse.com/#search=nth-child for compatibility. (no IE 6,7,8)

Answered By – c4urself

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.