1
$('tr > td:gt(0)').filter(function() {
                        return this.innerHTML.match(/^[0-9\s\.,]+$/);
                        }).css('text-align','right');

I am trying to loop through a dynamic table and right align every td that contains numeric data on each row EXCEPT the first td on each row.

It works on the first tr but not each subsequent row...

1
  • On behalf of user2374907: Does this work? $('tr > td').each(function() { if(!$(this).is(':first') && $(this).innerHTML.match(/^[0-9\s\.,]+$/) { $(this).css('text-align','right'); } }); Commented Mar 29, 2014 at 20:19

1 Answer 1

1

The reason this isn't working is that your jQuery selector is collecting all td elements (that are children of trs), and then sub-selecting all but the first one. To avoid this, you can iterate over the rows of the table, applying your filter to the td elements of each one:

$('tr').each( function () { 
    $(this).children('td:gt(0)').filter(function() {
        return this.innerHTML.match(/^[0-9\s\.,]+$/);
    }).css('text-align','right')
});

If you only want to apply this to a certain table, change the selector in the first line to '#table-id tr'.

Here it is in action: http://jsfiddle.net/munderwood/d48Q4/1/

Sign up to request clarification or add additional context in comments.

3 Comments

Works like a charm and your explanation makes sense. Thanks.
As a follow up, how would I subsequently move the corresponding <th> in the <thead> row to the right too. Of course, the <th> is a text label so it doesn't meet the regex. Thanks in advance.
fails with negative values

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.