Find element that has either class 1 or class 2

JqueryJquery Selectors

Jquery Problem Overview


I'm 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 am unsure if/how I can check for one of 2 classes (my element will only have one class out of these 2 I mentioned).

Thanks for your help!

Jquery Solutions


Solution 1 - Jquery

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) then look at the answer provided by @jelbourn.

Solution 2 - Jquery

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

var elements = $(this).find('.myclass1:first, .myclass2:first');

Solution 3 - Jquery

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/

Solution 4 - Jquery

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

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

It would probably look something like this:

if($(this).hasClass('myClass1') || $(this).hasClass('myClass2')) {
  myText = $(this).text();
} else {
  myText = null;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaleView Question on Stackoverflow
Solution 1 - JqueryGabriele PetrioliView Answer on Stackoverflow
Solution 2 - JqueryJeremy ElbournView Answer on Stackoverflow
Solution 3 - JqueryMauroView Answer on Stackoverflow
Solution 4 - JqueryJames ThompsonView Answer on Stackoverflow