Get the name of a class, knowing part of it, if it is not the only class applied to an element
I'm looking for a way to use jquery / javascript to get the name of a class when I only know a part of it and multiple classes are applied to that element.
So, if I am looking for a class that I know starts with "charLimit_", I want to know that fully qualified class name, even if it is not the only class applied to a given element. Example HTML:
<input class="charLimit_30 lastNameValidation" type="text" />
What I have so far below will put both "charLimit_30" and "lastNameValidation" into the array, but how can I tell I need "charLimit_30" and then only say the value found after the underscore (30).
var classMName = $('[class*=charLimit_]').attr("class").split(' ');
Thanks in advance for your help!
+2
source to share
4 answers
This is similar to what inkedmn said, but in more jQuery-ish:
var numbersAfterCharLimit = [];
$('[class*="charLimit_"]').each(function() {
var matches;
if (matches = this.className.match(/(?:\s+|^)charLimit_([0-9]+)(?:\s+|$)/)) {
numbersAfterCharLimit.push(parseInt(matches[1], 10));
}
});
+2
source to share
This seems to work (at least on stackoverflow):
var test = $('[class*=owner]').attr('class').split(' ');
for(i in test){
if(test[i].indexOf('post-sign') !== false){
test = test[i].split('-');
// replace this with a return
console.log(test[1]);
break;
}
}
And one that will work with the code he is trying to do with:
var test = $('[class*=charLimit_]').attr('class').split(' ');
for(i in test){
if(test[i].indexOf('charLimit_') !== false){
test = test[i].split('_');
// replace this with a return if it is in a function
console.log(test[1]);
break;
}
}
+1
source to share