简体   繁体   中英

How can I apply CSS only to digits in jQuery?

I have this html

<tr>
   <td>Test</td> 
   <td>324</td>
</tr>

My default CSS is text-align:left

But I want to apply text-align:center to any <td> that contains digits.

I have about 50 HTML files so I can't add class manually.

You could use filter and some regex magic:

$('td').filter(function() {
  return /^\d/.test($(this).text());
}).css('text-align', 'center');

The above regex is a bit simple, if you need more precision use this one:

/((?!\w+[^\s]))\d+\1/

The above will match (space)123 and 123(space) but not 123a or asd 123 so basically only numbers and spaces allowed if that's what you're looking for. To add more valid characters just put them like [^\\s,] , that will make the comma , valid too.

old-school solution (works well):

function Trim(str){
    return str.replace(/^\s+|\s+$/g,"");
}

function applyCssCustomToSomeTds(){
    for(i=0;i<document.getElementsByTagName('td').length;i++){
        var elementTd = document.getElementsByTagName('td')[i];
        if(!isNaN(Trim(elementTd.innerHTML))){
            elementTd.style.textAlign = "center";
        }
    }
}
​$(function(){
    $("td").filter(function(){
        return (/^\s*\d*\.?\d+\s*$/).test(this.innerHTML);
    }).css("text-align","center");        
});​​

EDIT: here's a jsfiddle: http://jsfiddle.net/Avf7P/

As another example of adding a class through jquery you can check out this fiddle . The class 'centerMe' just includes the text-align value that you need.

 $('td').each(function(){
            if($.isNumeric($(this).html()))
            {
                $(this).addClass('centerMe');
            }
    });

Note that this uses the isNumeric which may not be your intent. If that's the case then you'd need to modify this to use one of the regex approaches mentioned in some of the other solutions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM