bgmCoder
bgmCoder

Reputation: 6371

jQuery `find` whilst matching one class or two classes

There is a table in my site, where, on some pages, it has two classes, and on other pages it has one class. I want to do a find on that table, but need to find in both cases, but I don't want to do to searches to discover the elements.

How can I write this? (I am no expert in js nor jquery; I appreciate your help) Here is what I've come up with so far, but it doesn't seem to work on both pages:

var tablerow1 = $('table [class="firstclass"]');
var tablerow2 = $('table [class="firstclass secondclass"]');

if(tablerow2){
    var tablerow = tablerow2;
}else{
    var tablerow = tablerow1;
};  

tablerow.find('tr').each(function(index, thiselement){
    ...
}

Upvotes: 0

Views: 41

Answers (1)

bpoiss
bpoiss

Reputation: 14003

Change

var tablerow1 = $('table [class="firstclass"]');
var tablerow2 = $('table [class="firstclass secondclass"]');

to

var tablerow1 = $('table.firstclass');
var tablerow2 = $('table.firstclass.secondclass');

But you could also just select firstclass. It will select tables with this class, also if it has some more other classes, so in your case, your table would be selected in both of your cases.

Upvotes: 1

Related Questions