36

I have several div's with "project[0-9]" classes:

<div class="project1"></div>
<div class="project2"></div>
<div class="project3"></div>
<div class="project4"></div>

I want to check if the element has a "project[0-9]" class. I have .hasClass("project") but I'm stuck with matching numbers.

Any idea?

ditto
  • 5,917
  • 10
  • 51
  • 88
  • 3
    Why don't you just give them one class `project`? – Bergi Dec 14 '12 at 12:32
  • @Bergi There are moments when you can't. The answer below helped me because I can only inject my own javascript in the page I'm working on, not change the html itself. – s1h4d0w Jul 08 '16 at 11:15

6 Answers6

64

You can use the startswith CSS3 selector to get those divs:

$('div[class^="project"]')

To check one particular element, you'd use .is(), not hasClass:

$el.is('[class^="project"]')

For using the exact /project\d/ regex, you can check out jQuery selector regular expressions or use

/(^|\s)project\d(\s|$)/.test($el.attr("class"))
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • So something like: if($(this) == $('div[class^="project"]')) ?? – ditto Dec 14 '12 at 12:39
  • 5
    Note that the startwith select will not work if `projectN` is not the first class name of the element, say `class="someclass project1"`. So the last regex version should be used in this case. – Panwen Wang Dec 10 '15 at 03:56
13

A better approach for your html would be: I believe these div's share some common properties.

<div class="project type1"></div>
<div class="project type2"></div>
<div class="project type3"></div>
<div class="project type4"></div>

Then you can find them using:

$('.project')
Akhil Sekharan
  • 12,467
  • 7
  • 40
  • 57
11
$('div[class*="project"]')

will not fail with something like this:

<div class="some-other-class project1"></div>
migli
  • 2,692
  • 27
  • 32
1
$('div[class^="project"]')

will fail with something like this:

<div class="some-other-class project1"></div>

Here is an alternative which extends jQuery:

// Select elements by testing each value of each element's attribute `attr` for `pattern`.

  jQuery.fn.hasAttrLike = function(attr, pattern) {

    pattern = new RegExp(pattern)
    return this.filter(function(idx) {
      var elAttr = $(this).attr(attr);
      if(!elAttr) return false;
      var values = elAttr.split(/\s/);
      var hasAttrLike = false;
      $.each(values, function(idx, value) {
        if(pattern.test(value)) {
          hasAttrLike = true;
          return false;
        }
        return true;
      });
      return hasAttrLike;
    });
  };



jQuery('div').hasAttrLike('class', 'project[0-9]')

original from sandinmyjoints: https://github.com/sandinmyjoints/jquery-has-attr-like/blob/master/jquery.hasAttrLike.js (but it had errrors so I fixed it)

Douglas.Sesar
  • 4,214
  • 3
  • 29
  • 36
0

You can improve the existing hasClass method:

// This is all that you need:
(orig => { 
  jQuery.fn.hasClass = function(className) {
    return className instanceof RegExp
      ? this.attr('class') && this.attr('class')
        .split(/\s+/)
        .findIndex(name => className.test(name)) >= 0
      : orig.call(this, className); 
  }
})(jQuery.fn.hasClass);

// Test the new method:
Boolean.prototype.toString = function(){ this === true ? 'true' : 'false' };
const el = $('#test');
el.append("hasClass('some-name-27822'): " + el.hasClass('some-name-27822'));
el.append("\nhasClass(/some-name-\d+/): " + el.hasClass(/some-name-\d+/));
el.append("\nhasClass('anothercoolclass'): " + el.hasClass('anothercoolclass'));
el.append("\nhasClass(/anothercoolclass/i): " + el.hasClass(/anothercoolclass/i));
el.append("\nhasClass(/^-name-/): " + el.hasClass(/^-name-/));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre id="test" class="some-name-0 some-name-27822 another-some-name-111 AnotherCoolClass"></pre>
Slavik Meltser
  • 9,712
  • 3
  • 47
  • 48
-7

why don't you use for to check numbers

for (var i = 0; i < 10; i++) {
                if(....hasClass("project"+i))
                {
            //do what you need
                }
            }
serhads
  • 462
  • 2
  • 7
  • 22