Link to home
Start Free TrialLog in
Avatar of ShanghaiD
ShanghaiDFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Better way to loop through table columns?

I'm using two .each() loops through table columns -- first column loop then second column loop -- to set column styles based on column values, as follows:
<script type="text/javascript">
$(document).ready(function(){
    $('tbody tr td:nth-child(1)').each(function() {
        if ($(this).text()>'480') {
            $(this).addClass('red');
            }
    });
    $('tbody tr td:nth-child(2)').each(function() {
        if ($(this).text()=='Boy') {
            $(this).addClass('blu');
            }
    });
});
</script>

Open in new window

Although this works successfully, it seems to be inefficient as it loops the same table rows twice.

What I would like to do is to loop the rows once only, and then in each .each() iteration I would like to test both column1 and then column2 to set their Class, but I cannot work out how to do that (something like):

<script type="text/javascript">
$(document).ready(function(){
    $('tbody tr').each(function() {
        // test first td column
 
        // test second td column
     
    });
});
</script>

Open in new window

Can anyone point me in the right direction?
ASKER CERTIFIED SOLUTION
Avatar of hielo
hielo
Flag of Wallis and Futuna image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ShanghaiD

ASKER

Thank you!  I will post a foliow up query to expand on this solution.