Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery match part of class with hasClass

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?

like image 755
ditto Avatar asked Dec 14 '12 12:12

ditto


4 Answers

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")) 
like image 195
Bergi Avatar answered Oct 12 '22 12:10

Bergi


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') 
like image 21
Akhil Sekharan Avatar answered Oct 12 '22 11:10

Akhil Sekharan


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

will not fail with something like this:

<div class="some-other-class project1"></div>
like image 41
migli Avatar answered Oct 12 '22 10:10

migli


$('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)

like image 20
Douglas.Sesar Avatar answered Oct 12 '22 12:10

Douglas.Sesar