What is the best way to dynamically apply classes to various elements with jquery or javascript based on the current day of the week?

Let's say I have 4 divs, each with specific day/days when a class needs to be added. For example:


<code><div class="on-17 on-18"></div>
<div class="on-20"></div>
<div class="on-21"></div>
<div class="on-22"></div>

I want to add the "active" class to the first div if today is the 17th or 18th of the current month. Any suggestions? It doesn't necessarily need to involve extracting "on-17" to get the number 17, it can be done manually by checking for certain 'on#' values, such as 17, 18, 20, 21, 22.

For instance, if today were March 17, 2015, it would trigger the addition of the active class to

<div class="on-17 on-18"></div>
resulting in
<div class="on-17 on-18 active"></div>

Answer №1

Using plain Javascript instead of jQuery to determine the current date can be a simple and effective approach.

var today = new Date();

if(today.getDate() === 17) {
  $('.on-17').addClass('active');
}

A more dynamic way to apply the class active to the current day's div:

var today = new Date();
var dayOfMonth = today.getDate();

$('on-' + dayOfMonth).addClass('active');

If you prefer having different styled classes for each day based on its number:

var today = new Date();
var dayOfMonth = today.getDate();

$('on-' + dayOfMonth).addClass('active-' + dayOfMonth); //For instance, this will add the class active-17 on the 17th day of each month

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to ensure that the 'pointermove' event continues to trigger even after the dialog element has been closed?

I am working on a project that involves allowing users to drag elements from a modal dialog and drop them onto the page. I have implemented a feature where dialog.close() is called once the user starts dragging. This functionality works perfectly on deskto ...

data.map` does not work as a function

I've encountered a persistent error that has me stumped. Here's the code snippet: JSON {"inventory": [ { "item_id" : "123", "item_data" : { "image_id" : "1234", "description" : "foo", "lin ...

Is there a method available to selectively `cache` specific tabs?

Is there a way to selectively cache tabs in jQuery-UI? For example, I have 3 tabs and I only want to cache tab number 2. I am aware that we can use the following code: $( ".selector" ).tabs({ cache: true }); However, this caches all tabs, not just the ...

How to vertically center align divs of unpredictable height

Currently grappling with a dilemma related to the vertical-align attribute and floating div elements. The heights of these divs are unknown as they are dynamically created based on text content. If you want to take a look at the code snippet, here is the ...

Show Pictures Side by Side with Captions Below

I need help organizing multiple images in a row with text underneath for my college project. I've been experimenting with some code but haven't had any success yet. <div class="test"> <p> <a href="https://www.facebook.com" ...

How can the HTML DOM be used to implement a dynamic table with a drop feature?

I am struggling to capture the drop event, and I'm unable to do so. Please assist me. I need the savechanges() function to be triggered with every drop action. $('#drag').sortable(); function savechanges() { var table = document.getEleme ...

Instructions on deploying static files to Vercel including HTML, CSS, and JavaScript files

I have encountered an issue and would like to share my solution - please see my initial response. Currently, I am facing a challenge while trying to deploy a repository from my GitHub account. The repository consists of various static files: ├─js ...

Is it possible to log out a user in JavaScript by simply removing cookies?

Hey there, I currently have a node.js server running in the background which handles user login processes (I didn't create the backend code). app.use(function (req, res, next) { var nodeSSPI = require('node-sspi'); var nodeSSPIObj = n ...

Steps for populating a table with data from a JSON array

I am currently facing a challenge in populating an HTML table with data retrieved from a two-dimensional array. The information is being fetched through an $.ajax script after executing a php/MySQL query. Despite successfully parsing the data in the succes ...

Attempting to divide a sentence based on the specified output criteria below

I am trying to split a sentence into individual words and create a new array. If the word is found in another array, I want to replace it with an empty string and add space where necessary. The desired output should look like this: Arr=["I want to ea ...

I am unable to access a certain piece of data directly, as I must use an intermediary variable in the process

As someone who is just starting out in programming, I may not have the best questions. Please bear with me if I am taking up your time unnecessarily. I have a query regarding the usage of labels indirectly in DatatoBarChartJS (using a "label") that confuse ...

Avoid the visibility of content in one div overlapping with content in another div

I'm looking for a way to prevent the central text from surpassing the red limits. When viewing at full screen, everything looks fine, but upon resizing I want the text to remain within a defined "block". <div class="centered"> <div style=" ...

unable to properly evaluate the string results from the AJAX request

Utilizing AJAX to verify a user's login information for accuracy, I am encountering an issue where the comparison between the returned "success" String and the expected value using == or === always results in failure. The AJAX implementation is as fo ...

Ways to organize JSON information in JavaScript

The JSON data I have is structured like this. {"count": 3, "records": [ {"common":{"review_date": "2016-02-07 07:00:00","severityid": {"value": "2", "description": "Medium"}}}, {"common":{"review_date": "2016-02-07 08:00:00","severityid": {"value": "2" ...

Creating a collapsible accordion feature with jQuery using a specific HTML layout: wanna learn how?

I am looking to create an accordion effect with the structure provided below. The goal is to have the corresponding article toggle when clicking on .booklist>li>a, allowing only one article to be open at a time. Can someone assist me with writing thi ...

What is the best way to include the border-radius CSS property to a dropdown element in Ant Design?

Adding the border-radius CSS property to my dropdown component from ant design has been a bit challenging for me. I attempted to modify the antd-css file and include a style object directly into the component, but unfortunately, I did not achieve the des ...

What could be causing the unexpected text display in my shiny app despite using html tags and bootstrap?

Here is a simple example that illustrates the error I am experiencing: library(shiny) run_with_enter <- ' $(function() { var $els = $("[data-proxy-click]"); $.each( $els, function(idx, el) { var $el = $(el); var $proxy = $("#" + $el.data("proxyCl ...

Trigger a series of child functions upon clicking the parent button

I am facing an issue where I am attempting to trigger the functions of each child component from a button click event on the parent component. I have tried using props and setting up a new function in the componentDidMount lifecycle method, but only the la ...

Fade images using jQuery when hovered over

Is there a way to create an interactive image that cycles through multiple images when hovered over, and returns to the original image when the mouse moves away? I'm aiming for a smooth fade effect between images, like transitioning between 3 or 4 dif ...

Guide to separating the bytes of a number and placing them into an Uint8Array

I am looking to convert a JavaScript number into the smallest possible uint8array representation. For example : 65 535 = Uint8Array<[255,255]> (0b1111111111111111 = [0b11111111, 0b11111111]) 12 356 = Uint8Array<[48,68]> (0b0011000001000100 = [ ...