• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 664
  • Last Modified:

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?
0
ShanghaiD
Asked:
ShanghaiD
1 Solution
 
hieloCommented:
try:
$('tbody tr td').each(function(i) {
	if( !(i % 2) )
	{
	        if (1*$(this).text()>480) {
    	        	$(this).addClass('red');
        	}
	}
	else
	{
	        if ($(this).text()=='Boy') {
    	    	    $(this).addClass('blu');
        	}
	}
    });

Open in new window

0
 
ShanghaiDAuthor Commented:
Thank you!  I will post a foliow up query to expand on this solution.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now