jQuery finding class name value from class array
I am trying to find the exact value of a class name containing the text iconGroup
and I am able to get an array of class names using:
var chosenIconClassArray = $('.selectedGroupIcon').attr('class').split(/\s+/);
console.log(chosenIconClassArray);
$.each(chosenIconClassArray, function(index, item) {
console.log(item);
});
This gives a console output of:
["createAGroupIconList", "inlinelis开发者_运维知识库t", "ram", "left", "iconGroup20", "selectedGroupIcon"]
createAGroupIconList
inlinelist
ram
left
iconGroup20
selectedGroupIcon
I have tried something along the lines of this to find which iconGroup
it is, but it didn't work:
if (item ^= 'iconGroup') {
console.log($(this));
}
The goal is to be able to tell that the class array contains the value iconGroup20
(or any number such as 1, 2, 3, 4, etc) which I can then add to another element to update it's icon.
How can I go about searching that array and then find which iconGroup
class is in it?
Are you looking for something that finds classes on an item that match the format 'iconGroup##'? If so, try something like this:
function getIconGroup(class_array) {
var iconGroup = false;
$.each(class_array, function(index, item) {
if item.match(/^iconGroup[0-9]+$/) {
iconGroup = item;
}
});
return iconGroup;
}
Updated to act as a function so you can use getIconGroup(ChosenIconClassArray)
.
JavaScript has a String.indexOf
method. It'll return the index of the string you give it, or -1 if the string wasn't found.
The following piece of code should give you the class you're hoping for.
var chosenIconClassArray = $('.selectedGroupIcon').attr('class').split(/\s+/),
foundClass;
$.each(chosenIconClassArray, function(index, item) {
if (item.indexOf('iconGroup') > -1) {
foundClass = item;
}
});
The variable foundClass
should contain the full class.
精彩评论