Reputation: 99
I have a div with the following classes:
form-group val-presence-text val-type-pos-int val-length-10 has-success has-feedback
I want to get the 10
from the val-length-10
class name. I've tried various methods, but none seem to work for a dynamic multi-class attribute such as this. In addition, the 10
could be any positive integer and the class could be located anywhere within the group of classes.
Any ideas?
Upvotes: 0
Views: 304
Reputation: 59232
You can use this:
var val_length = $('div').attr("class").match(/val-length-(\d+)/)[1];
Upvotes: 3
Reputation: 749
Assuming that the it is 'val-length' that never changes and just the integer on the end of it, you should be able to do this:
//get an array of classes on a specific element
var classList =$('#elementId').attr('class').split(/\s+/);
//loop through them all
$.each( classList, function(index, item){
//check if any of those classes begin with val-length-
if (item.indexOf('val-length' === 0) {
console.log(item.substring(11))
}
});
Upvotes: 0
Reputation: 26143
Try this...
$("div[class*=val-length-]").each(function() {
var s = this.className;
var length = 0;
$(s.split(" ")).each(function() {
if (this.search("val-length-") === 0) {
length = this.substr(11);
}
});
console.log(length);
});
It will find the relevant div and pull the value for you.
Upvotes: -1
Reputation: 145398
One possible solution:
var n = (this.className.match(/val-length-(\d+)/) || []).pop();
Or in the context:
$('[class*="val-length-"]').each(function() {
var n = (this.className.match(/val-length-(\d+)/) || []).pop();
console.log(n);
});
Upvotes: 2