0

Is there a way of checking whether the object's specific class is in array - I've done it with object's 'id', but can't do with 'class' - with 'id' it goes like this:

var arr = [ 'error', 'button', 'items', 'basket' ];
if (jQuery.inArray($(this).attr('id'), arr) == -1) {
      // do something here
}

I would like to have something like the following, which doesn't work:

var arr = [ 'error', 'button', 'items', 'basket' ];
if (jQuery.inArray($(this).attr('class'), arr) == -1) {
      // do something here
}

Any idea?

Just to show you what I'm using it for:

var arr = [ 'error', 'button', 'items', 'basket' ];
$.each(data, function(k, v) {
    if (jQuery.inArray($(this).attr('class'), arr) == -1 && $('.' + k).length > 0) {
        $('.' + k).fadeOut(100, function() {
        $(this).hide().html(v).fadeIn(100);
        });
    }
});
7
  • 2
    aside from telling you to check "hasClass()" I'm not sure that you can do it this way ... Commented Apr 4, 2011 at 15:27
  • @user, what is your main goal, ignoring this array function? What are you trying to achieve eventually? Maybe there are some nice functions for this. Commented Apr 4, 2011 at 15:28
  • 1
    Are you looking for something like "hasClass" but which accepts an array? api.jquery.com/hasClass Commented Apr 4, 2011 at 15:28
  • OT: There are faster ways to check whether an element has a specific ID. The trivial solution for classes would be to loop over all of them and check whether the element has this class with hasClass. Where is the problem? Commented Apr 4, 2011 at 15:30
  • Yes - exactly this. I'm basically looping through the array returned by ajax call and want to update all elements by returned array key which is not included within the manually defined array. Commented Apr 4, 2011 at 15:31

3 Answers 3

5
$(this).is(
     [ 'error', 'button', 'items', 'basket' ]
     .map(function(cls) {return "." + cls;})
     .join(',')
);
  1. $(this).is(selector) checks if the given object or set of object matches the selector.
  2. To construct the selector we take an array of the classes were interested [ 'error', 'button', 'items', 'basket' ]
  3. As the classes are selected with .<class_name> we prepend the dot to each class name using map array.map(function(cls) {return "." + cls;})
  4. To make this a full selector we can join the array elements using a comma as a separator with array.join(',')

The result is $(this).is('.error, .button, .items, .basket') which matches if $(this) has any of the classes defined.

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

4 Comments

very tidy - maybe add a couple of comments to let people know what this is doing.
sorry, had to go change a diaper before testing and commenting.
Really nice - many thanks, but how would I know check whether the element which is currently in a loop matches the element of the array using this code? I've tried: if (k.is([ 'error', 'button', 'items', 'basket' ]) , where 'k' is current array key in a loop. I've also tried : if (k.is([ 'error, button, items, basket' ])) as 'k' in a loop is always just a name of the class - without preceeding dot (.)
Guys - sorted it out - sometimes when you spend too many hours in front of the computer you just try try to solve problems in the most complicated way possible as I'm sure many of us know. I was just looking for a class - while I simply had to check whether the key is in array - I think I need a break. Thanks everyone for the contribution! - my code simply had to check : if (jQuery.inArray(k, arr) == -1) to find out if element is not in array.
1

Not tested, but something like this should work.

function hasClassInArray(classArray, objId)
{
   // Get an array of all the object's classes
   var classes = $('#' + objid).attr('class').split(/\s+/);

   // Iterate through the object's classes and look for a match
   for(var i = 0; i < classes.length; i++)
      if($.inArray(classes[i], classArray))
         return true;

   return false;
}

Since an object can have more than one class you have to get all its classes and check to see if they're in the other array. Sadly JS has no native intersect() function.

1 Comment

Thanks crocodilewings - it's not exactly what I'm looking for thou - please see comments above.
1

When you are using .attr('class'), you are using the whole class string and not individual ones. You need to loop through the classes and check if they are in the array:

var arr = [ 'error', 'button', 'items', 'basket' ],
    classes = $(this).attr('class').split(' ');

for (var i = 0, len = classes.length; i < len; i++) {
    if ($.inArray(classes[i], arr) === -1) {
        // do something here
    }
}

To grab all the elements matching the array keys:

var arr = [ 'error', 'button', 'items', 'basket' ];
var elements = $();

$.each(arr, function(index, value) {
    elements.add('.' + value);
});

2 Comments

That's good - however, I'm not working with the specific element - so I can't really use $(this) here - as it is looping through the output of array returned by ajax call and tries to find the elements with the same class as array key on the page - then feed the value into that element.
There's no reason to split the class attribute and do a linear array search. Just use a regex. Also, class is a future reserved word in JavaScript, so this code will fail.

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.