Obeck
Obeck

Reputation: 67

jquery if element contains number

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.

fiddle

<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

Answers (5)

user1939371
user1939371

Reputation: 95

$( "li a" ).each(function() {

var xc = $(this).text();

  if ( $.isNumeric(xc) ) {
    $(this).attr('class', 'numb');
  } else {
$(this).attr('class', 'noNumb');
  }
});

Upvotes: 0

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

You can use isNumeric function for that.

demo

$("li a").each(function() {
var num = $(this).text();
if ($.isNumeric(num)) {
        $(this).addClass('numb');
    } else {
        $(this).addClass('noNumb');
    }
});

demo

Upvotes: 6

softsdev
softsdev

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');    
    }
});

Fiddle

Upvotes: 4

Alan Doyle
Alan Doyle

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

msapkal
msapkal

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

Related Questions