1

I have a series classes start myclass, like myclass-s1, myclass-b10, myclass-ss1 etc. Does jQuery hasClass check if class name start 'myclass-' ?

BoltClock
  • 665,005
  • 155
  • 1,345
  • 1,328
olo
  • 5,043
  • 14
  • 47
  • 80

4 Answers4

4

You can use is method

if($('div').is('[class^=myclass]')){
//do your stuff here
}
Bhojendra Rauniyar
  • 78,842
  • 31
  • 152
  • 211
3

Or you can use plain javascript:

 /\bmyclass-.+\b/.test(element.className)
dfsq
  • 187,712
  • 24
  • 229
  • 250
  • 1
    Or .matches , which is effectively 'vanilla' 'is' – Benjamin Gruenbaum Apr 22 '14 at 05:00
  • This is actually the most accurate solution. While possible, it's difficult to represent a class name prefix using attribute selectors given the nature of the `class` attribute. – BoltClock Apr 22 '14 at 05:01
  • @Sani Huttunen: True, I was speaking in the context of this question alone. Here's a solution using attribute selectors as opposed to `className` matching: http://stackoverflow.com/questions/4524412/jquery-selector-to-target-any-class-name-of-multiple-present-starting-with-a-p/4524477#4524477 – BoltClock Apr 22 '14 at 05:12
1

You can just use straight JavaScript for this:

if ( myElement.className.match(/\bmyclass-.*/) ) {
    // do stuff
}

or

if ( $(mySelector).attr("class").match(/\bmyclass-.*/) ) {
    // do stuff
}
Joel Cornett
  • 23,166
  • 9
  • 59
  • 85
0

You could use below code if you want to check if class namme starts with...
You want to check the classes that starts with myclass- ,so it would give you the number of occurrence according to your input in the alert. According to this the output is 2.

<div class="myclass-s1"></div>
<div class="myclass-b10"></div>
<div class="myclassb10"></div>

$.expr[':'].hasClassStartingWithInput = function(obj){
return ((/\bmyclass-/).test(obj.className)); //here is the input(myclass-)that you need to give
 };

 alert($('div:hasClassStartingWithInput').length);
Reena
  • 1,109
  • 8
  • 16