1

Suppose I have a Jquery Object $('.class0 .class1 .class2...'). I want to check if a class .classX is in this object. How can I do this? I don't think inArray() is not adapted

In the same time, just to make things clearer for me, if I have a Jquery Object $('.class0, .class1, .class2, ...') if I want to check if a class .classX is in this object, I should use inArray() method, right?

2
  • Why exactly do you need to know for sure? I mean, if it's required for that class to be existent in your result set, then you should use a selector that only returns elements with that class... Commented Jan 21, 2013 at 18:37
  • Do you need to check if .classX was in the selector even if there are no matching elements of .classX? It's easy to find if your jquery object contains any elements of classX but a different question if you need to know if the selector contained the class. Commented Jan 21, 2013 at 18:37

3 Answers 3

6

If there is a set of elements in jQuery object, you can use filter():

var isInside = $(".class0, .class1, .class2, ...").filter(".classX").length > 0;
Sign up to request clarification or add additional context in comments.

16 Comments

I'm not sure why this is getting more upvotes than .hasClass() and .is()
Using filter, you can still returning set of objects
The OP didn't say he wanted a set of objects with the specified class. He simply wants to know if an object with the class exists.
He could also do $(".classX", this); inside the context of the first jQuery object to get the "filtered" results as well.
@crush I'm not sure that you are right. $(".class0 .class1 .class2") will return an element with class class2, hence it doesn't make any sense to check if the element has class class0 or whatever. I guess the OP misspelled. There should be commas in the selector.
|
4

Use .hasClass().

var hasClass = $obj.hasClass("classX");

Notice there no dot (.) character prefixing classX.

4 Comments

this is returning false var tmp = $('.class0 .class1 .class2'); alert($(tmp).hasClass('.class2'));
@user1611830, notice there's no dot (.) prefixing class2. It's hasClass('class2') not hasClass('.class2')
@user1611830 BTW, you don't need to do $(tmp) in your example. tmp is already a jQuery object.
Great thank you ! Where can I find some docs about Jquery objects and methods, i need to understand better !
3
$('.class0, .class1, .class2').is('.class2');

FIDDLE

Comments

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.