Reputation: 67
I want to find out if an element contains a number no matter how long it is. I need a distinction between words and numbers or other characters.
<ul>
<li><a href="#">Word</a></li> <!-- this is a word -->
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">...</a></li> <!-- this is a word -->
<li><a href="#">15</a></li>
<li><a href="#">30</a></li>
<li><a href="#">100</a></li> <!-- this is a number -->
<li><a href="#">Word</a></li>
</ul>
Upvotes: 0
Views: 5421
Reputation: 95
$( "li a" ).each(function() {
var xc = $(this).text();
if ( $.isNumeric(xc) ) {
$(this).attr('class', 'numb');
} else {
$(this).attr('class', 'noNumb');
}
});
Upvotes: 0
Reputation: 85545
You can use isNumeric function for that.
$("li a").each(function() {
var num = $(this).text();
if ($.isNumeric(num)) {
$(this).addClass('numb');
} else {
$(this).addClass('noNumb');
}
});
Upvotes: 6
Reputation: 1509
You can also do this by using REGEX
Reguler exp '/\d/'
$(this).text().match(/\d/)
$( "li a" ).each(function() {
var matches = $(this).text().match(/\d/);
if (matches){
$(this).attr('class', 'numb');
}else{
$(this).attr('class', 'noNumb');
}
});
Upvotes: 4
Reputation: 108
as C-link said, isNumeric..
$("li a").each(function() {
var toCheck = $(this).text();
if (isNumeric(toCheck)) {
$(this).attr('class', 'is_number');
} else {
$(this).attr('class', 'is_not_number');
}
});
Upvotes: 0
Reputation: 8346
Try this out. Use isNaN
to check if it's a number or not.
$( "li a" ).each(function() {
var xc = $(this).text();
var isNum = isNaN(xc);
if (isNum) {
$(this).attr('class', 'numb');
} else {
$(this).attr('class', 'noNumb');
}
});
Upvotes: 1