0

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", "inlinelist", "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?

2 Answers 2

2

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Corey, how can I prevent the item from being overwritten with null when the class array contains classes after the iconGroup## in the each loop?
1

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.

2 Comments

Thanks James, I had tried out indexOf but was unsure if it would be cross-browser. Also, this function (had) an illegal break statement so it wouldn't work.
Sorry, try replacing break; with return false;. That should help. String.indexOf has huge browser support, so use it with confidence

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.