msmahon
msmahon

Reputation: 434

Adding class to <td> based on Id and switch

I have a table representing weekdays (only 5 days at a time). I would like to highlight the day of the week depending on what day it is. I am attempting to use a Switch function to select the element by its Id then add a class. Perhaps someone can identify the problem or provide a more elegant solution. Thank you!

HTML:

<tr>
  <th>CHANGES</th>
  <td id="mon">2</td>
  <td id="tues">3</td>
  <td id="wed">4</td>
  <td id="thurs">5</td>
  <td id="fri">6</td>
</tr>

Javascript

// Set "today" to day of week abbreviation
var today = String(Date.today()).slice(0,3);

// Add class to td based on day of week.
switch (today) {
    case "Mon":
        jQuery("#mon").addClass("today");
        break;
    case "Tue":
        jQuery("#tues").addClass("today");
        break;
    case "Wed":
        jQuery("#wed").addClass("today");
        break;
    case "Thu":
        jQuery("#thurs").addClass("today");
        break;
    case "Fri":
        jQuery("#fri").addClass("today");
        break;
}

*Note: I am using Date.js lilbrary to get the current day.

Upvotes: 0

Views: 88

Answers (2)

Anton
Anton

Reputation: 32581

Try this

var today = new Date();
today = today.toString().slice(0,3).toLowerCase();
$('#'+today).addClass('today');
.today{
  color:red;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table>
  <tr>
  <th>CHANGES</th>
  <td id="mon">2</td>
  <td id="tue">3</td>
  <td id="wed">4</td>
  <td id="thu">5</td>
  <td id="fri">6</td>
  </tr>
 </table>

You'll need to change the id of thursday to thu and tues to tue

<td id="tue">3</td>
<td id="thu">5</td>

Upvotes: 2

Justinas
Justinas

Reputation: 43441

If you can change HTML, than rename your id's as Mon, Tue, Wed, Thu, Fri, also add class days to all elements and than

var today = String(Date.today()).slice(0,3);
$('.days').removeDay('today');
$('#' + today).addClass('today');

Upvotes: 0

Related Questions