Find an element that has either class 1 or class 2

I am trying to find text inside an element whose class is either myClass1 or myClass2.

var myText = $(this).find('.myClass1:first').text(); 

This works fine, but I'm not sure / how I can test one of the 2 classes (my element will only have one class from the 2 that I mentioned).

Thanks for your help!

+47
jquery jquery-selectors
Nov 16 '10 at 16:24
source share
4 answers

If you want the first one found (but only one), use

 var myText = $(this).find('.myClass1,.myClass2').eq(0).text(); 

If you want the first of each kind (two results), take a look at @jelbourn .

+62
Nov 16 '10 at 16:28
source share

You can separate your selectors with commas to generate a list containing all elements with any class (or both):

 var elements = $(this).find('.myclass1:first, .myclass2:first'); 
+23
Nov 16 '10 at 16:27
source share

Enter a comma between the two classes in your selector.

 $(".a, .b") 

this will match all elements with class "a" OR class "b"

http://api.jquery.com/class-selector/

+7
Nov 16 '10 at 16:30
source share

Use the if statement and the jQuery hasClass () function:

http://api.jquery.com/hasClass/

It probably looks something like this:

 if($(this).hasClass('myClass1') || $(this).hasClass('myClass2')) { myText = $(this).text(); } else { myText = null; } 
+4
Nov 16 '10 at 16:30
source share



All Articles