john
john

Reputation: 834

How to check element with multiple classes for a number in class

Is it posible to get the class name in this element if its a number? Can you check if this element has a number as a class and get it out ?

<button id="12" class="btn btn-default 1000 tBtn">

Upvotes: 1

Views: 271

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 240888

You could use the attribute selector, [class], to select all elements with class attributes. From there you can filter the selected elements based on whether the the array of classes contain a number as a value by using the $.isNumeric jQuery method:

var $elements = $('[class]').filter(function () {
  var classes = this.className.split(' ');
  var classesWithNumbers = classes.filter(function (value) {
    return $.isNumeric(value);
  });

  return classesWithNumbers.length;
});

Here is a shorter, less verbose version:

var $elements = $('[class]').filter(function () {
  return this.className.split(' ').filter($.isNumeric).length;
});

It's worth mentioning that as of HTML4 classes and ids cannot start with numbers. However, that is no longer the case with HTML5. For reference, see: What are valid values for the id attribute in HTML?

Upvotes: 2

Related Questions