Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find element that has either class 1 or class 2

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!

like image 764
ale Avatar asked Nov 16 '10 16:11

ale


People also ask

How do you find an element with multiple classes?

Use the getElementsByClassName method to get elements by multiple class names, e.g. document. getElementsByClassName('box green') . The method returns an array-like object containing all the elements that have all of the given class names. Here is the HTML for the examples in this article.

How do you determine the class of an element in Cypress?

How can I check that the element has any of the two classes? cy. get(selector). invoke('attr','class').


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

like image 188
Gabriele Petrioli Avatar answered Oct 11 '22 15:10

Gabriele Petrioli


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'); 
like image 30
Jeremy Elbourn Avatar answered Oct 11 '22 15:10

Jeremy Elbourn