Reputation: 31548
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.
Upvotes: 0
Views: 274
Reputation: 48
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";
}
}
}
Upvotes: 1
Reputation: 2343
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.
Upvotes: 0
Reputation: 94101
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.
Upvotes: 3
Reputation: 2220
$(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/
Upvotes: 0