4

Is there a way to get the element using its classes not knowing the arrangement of classes?

I have here a sample HTML

<table>
  <tr class="header first test1">
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr class="header first test2">
    <td>January</td>
    <td>$100</td>
  </tr>
  <tr class="h34der third test1">
    <td>February</td>
    <td>$80</td>
  </tr>
</table>

I need to get the element that has header and test1 as its classes

Options I did was the following:

Option #1

$('.header, .test1').css('background','yellow');

However it is incorrect as it color all the elements that has "header" or "test1" class.

Option #2 I saw that this is possible

$("[class*='header first test1']").css('background','yellow');

But my scenario was I do not know the class "first" and the only classes I know are "header" and "test1".

Is there a way to identify the element using multiple classes? Appreciate your help with this.

Here is my fiddle I used for testing: http://jsfiddle.net/ky8d94n6/

2
  • $('.header.test1') Commented Jun 20, 2018 at 10:18
  • 4
    Do some research before posting a question. Commented Jun 20, 2018 at 10:20

1 Answer 1

3

Use $('.header.test1') to select element will class header and test1:

$(document).ready(function(){
    $('.header.test1').css('background','yellow');
});

$(document).ready(function(){
	$('.header.test1').css('background','yellow');
});
table, th, td {
    border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr class="header first test1">
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr class="header first test2">
    <td>January</td>
    <td>$100</td>
  </tr>
  <tr class="h34der third test1">
    <td>February</td>
    <td>$80</td>
  </tr>
</table>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.