I have a series classes start myclass, like myclass-s1
, myclass-b10
, myclass-ss1
etc.
Does jQuery hasClass check if class name start 'myclass-' ?
Asked
Active
Viewed 622 times
4 Answers
4
You can use is method
if($('div').is('[class^=myclass]')){
//do your stuff here
}

Bhojendra Rauniyar
- 83,432
- 35
- 168
- 231
3
Or you can use plain javascript:
/\bmyclass-.+\b/.test(element.className)

dfsq
- 191,768
- 25
- 236
- 258
-
1Or .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
- 24,192
- 9
- 66
- 88
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