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


If you only want the first occurrence, and everything that follows the underscore in the class is a number, then something like this:



$('[class*=charLimit_]').attr("class").match(/(?:\s|^)charLimit_(\d+)/)[1];

      

+2


source


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


var classes = $('input').attr('class');
var myNum = '';
for(var i=0;i<classes.length;i++){
    if(classes[i].match(/^charLimit_.*$/){
        myNum = classes[i].split('_')[1];
    }
}

      

Something like this will work, unless of course there is some magic jQuery way that I just don't know :)

0


source







All Articles