identify the row preceding the expiration month of a domain using JavaScript or jQuery

Is there a way to highlight the row representing the domain whose expiry month is before the current month, using the date and time information provided in the table (

<td>2017-04-14 17:21:00</td>
) with JavaScript or jQuery?

<table>
  <tr>
    <th>Domain</th>
    <th>Renewal Date</th>
  </tr>
  <tr>
    <td>mydomain.com</td>
    <td>2017-04-14 17:21:00</td>
  </tr>
  <tr>
    <td>mydomain.net</td>
    <td>2017-08-14 17:21:00</td>
  </tr>
</table>

Answer №1

Our current approach involves the following steps:

  1. Create a Date object for today's date.
  2. Select all td elements that contain a date, identified as the second td.
  3. Retrieve the expiration date and create a new Date object using that string value.
  4. Generate a Date object representing a month from now by adding 1 month to the current date.
  5. Determine if the expiration date falls before today or within the next month and assign the corresponding highlight class.
  6. If a highlight class is specified, apply it to the element.

This solution implements two types of highlights:

  1. For expiration dates within a month ahead.
  2. For expired dates.

var today     = new Date(),
    toISO8601 = function ( dateStr, offset ) {
        return dateStr.replace( ' ', 'T' ) + ( offset ? offset : 'Z' );
    };

$( 'td:nth-child( 2 )' ).each( function( i, el ) {

  var $el       = $( el ),
      expireStr = toISO8601( $.trim( $el.text() ), '-05:00' ),
      expires   = new Date( expireStr ),
      inAMonth  = new Date( today.getTime() ),
      highlight;
      
  inAMonth.setMonth( inAMonth.getMonth() + 1 );

  highlight = expires < today ? 'has-expired' :
              expires < inAMonth ? 'about-to-expire' :
              false;
                  
  if ( highlight ) {
  
    $el
      .parent()
      .addClass( highlight );
      
  }  

} );
.has-expired {
  background-color: indianred;
}
.about-to-expire {
  background-color: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <th>Domain</th>
    <th>Renewal Date</th>
  </tr>
  <tr>
    <td>mydomain.com</td>
    <td>2017-04-14 17:21:00</td>
  </tr>
  <tr>
    <td>mydomain.net</td>
    <td>2017-08-14 17:21:00</td>
  </tr>
  <tr>
    <td>mydomain.net</td>
    <td>2017-03-10 17:21:00</td>
  </tr>
  <tr>
    <td>mydomain.net</td>
    <td>2017-04-15 17:21:00</td>
  </tr>
  <tr>
    <td>mydomain.net</td>
    <td>2018-06-28 17:21:00</td>
  </tr>
  <tr>
    <td>mydomain.net</td>
    <td>2017-04-17 10:21:00</td>
  </tr>
</table>

You have the option to utilize toISOString(), such as expires.toISOString(), in place of the custom toISO8601() method, although toISOString() displays time in UTC while our function allows setting your own timezone offset.

Dealing with time can be complex, and depending on requirements, a library like moment.js may be necessary.

Answer №2

If you want to modify a specific element using JavaScript, the first step is to assign it an id for easy access:

<tr>
    <td id="expirationDate">mywebsite.com</td>
    <td>2017-08-14 17:21:00</td>
  </tr>

Next, in your JavaScript code:

   expirationDate = document.getElementById("expirationDate");
  // convert expirationDate.innerHTML to date and check if it's within a month, then wrap it with <mark> tags
   expirationDate.innerHTML = "<mark>" + expirationDate.innerHTML + "</mark>"

Answer №3

To tackle this issue, you can develop a JavaScript function that will:

  1. Parse through the relevant HTML elements containing date information and extract their values
  2. Convert each date value into a Date object for comparison with today's date
  3. If the time difference between two dates is within a month, apply a specified CSS highlight class to the parent tr element of the checked td element
  4. Ensure that the CSS highlight class is configured as desired
  5. Execute the JavaScript function upon document load completion

Answer №4

Check out the code snippet below and give it a try. Enjoy!

$(document).ready(function() {
  $("table tr").each(function(i) {
    var _this = $(this);
    if (i != 0) {
      var selectDate = $(_this).children("td").eq(1).text();
      if (Date.parse($.trim(selectDate)) < Date.parse(new Date())) {
        $(_this).addClass('highlight');
      }
    }
  });
});
.highlight {
  background-color: #ffdd00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<table>
  <tr>
    <th>Domain</th>
    <th>Renewal Date</th>
  </tr>
  <tr>
    <td>mydomain.com</td>
    <td>2017-04-14 17:21:00</td>
  </tr>
  <tr>
    <td>mydomain.net</td>
    <td>2017-02-19 17:21:00</td>
  </tr>
  <tr>
    <td>mydomain.org</td>
    <td>2017-08-16 17:21:00</td>
  </tr>
  <tr>
    <td>mydomain.edu</td>
    <td>2017-02-15 17:21:00</td>
  </tr>
  <tr>
    <td>mydomain.co.in</td>
    <td>2017-08-22 17:21:00</td>
  </tr>
</table>

Answer №5

A JavaScript solution has been implemented after an edit was made to the question text.

To begin, a class tag named "date" should be added to all td cells that contain a date.

// Retrieve all cells with dates
today_date = new Date()
expiration_date = new Date().setFullYear(2100, 01, 14)
all_date_td = document.getElementsByClassName("date");
// Iterate over each html element
for (var x = 0; x < all_date_td.length; ++x) {
  var content = all_date_td[x].innerHTML;
  year = Number(content.replace(/[ ].*/, "").split(/-| /)[0])
  month = Number(content.replace(/[ ].*/, "").split(/-| /)[1].replace("0", ""))
  day = Number(content.replace(/[ ].*/, "").split(/-| /)[2].replace("0", ""))
  expiration_date = new Date()
  expiration_date.setFullYear(year, month, day)
  if (today_date < expiration_date) {
    all_date_td[x].style.backgroundColor = "yellow"
  }

}
<table>
  <tr>
    <th>Domain</th>
    <th>Renewal Date</th>
  </tr>
  <tr>
    <td>mydomain.com</td>
    <td class="date">2017-04-14 17:21:00</td>
  </tr>
  <tr>
    <td>mydomain.net</td>
    <td class="date">2017-08-14 17:21:00</td>
  </tr>
  <tr>
    <td>mydomain.net</td>
    <td class="date">2015-08-14 17:21:00</td>
  </tr>
</table>

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

CSS syntax highlighting in Visual Studio 2015 does not function properly when used within vbhtml razor pages

When editing my vbhtml pages, I've noticed that everything syntax-highlights properly except for the CSS enclosed in the <style>...</style> block. Inline CSS like <td style="color:yellow"... still highlights correctly, but not the CSS i ...

Create a responsive layout of inline-block elements that adjusts to resizing

I am currently focusing on developing the website found at: The progress so far includes successfully creating a list of div.project-item elements that adjust the number of columns based on window resizing due to the use of inline-blocks. My next goal is ...

Calculate the factorial of a number by leveraging the power of arrays in Javascript

I attempted to create a function that accepts a parameter and populates an array with numbers less than the parameter down to zero in descending order. I then used a for loop to multiply each element in the array by the next element, but unfortunately, m ...

Stop the click event using a confirmation dialog before proceeding with the operation

I'm trying to implement a confirmation dialog before deletion by using e.preventDefault() to prevent immediate deletion. However, I am facing an issue in the YES function where I would like to resume the click event's operation with return true w ...

What strategies should be employed for effectively storing data in HTML for dynamic content?

I am currently in the process of developing a sleek, dynamic brochure website that can update content on button clicks through Javascript. Whenever the button is clicked, it triggers a function in the .js file to insert the new content into the HTML. To ma ...

Can an HTML, CSS, and Javascript combination be used to create a sidebar addon for LibreOffice?

Is it possible to create sidebar add-ons for LibreOffice/OpenOffice using HTML, CSS, and Javascript? Alternatively, could we utilize the UNO API and an embedded browser to run a web app within LibreOffice for seamless interaction? We have already develope ...

What is the best method for converting a png file to base64 and incorporating it into an asp.net mvc project?

I'm trying to export an image list in HTML, and it seems that the best way to do this is by converting them to base64. However, I've been having trouble finding clear instructions on how to transform an image into base64 and insert it into HTML. ...

What is a way to utilize Three.js without relying on Node.js, Express, or any build tools?

Objective: Start by importing the necessary modules... Issue: When trying to import jsm files like OrbitControls.js using from 'three';, an error occurs: [Error] TypeError: Module specifier, 'three' does not start with "/", ...

Investigate the presence of a vertical scrollbar using JQuery or JavaScript

Within an HTML report, I have applied the style "overflow:auto" to allow for dynamic data filling. I am now facing the challenge of detecting whether a vertical scrollbar exists within the report. After scouring various forums for solutions, I came across ...

Is the z-index feature not functioning as anticipated?

I'm currently working on a project involving a book that flips on click on both sides. The process involves checking the direction when a page is clicked and flipping it to the left if it's not to the right. Additionally, I adjust the z-index to ...

Obtaining text color in Selenium using Python

My objective is to extract the text color from each cell in a single column table. The HTML structure for a cell is as follows: <table class="table table-bordered table-hover"> <tbody> <tr> <td class="ta ...

A step-by-step guide on converting an audiopath to an audio file in a React-Native application and transferring it

I am facing a challenge in my react-native application where I need to send an audio wav file to a postnodejs/express route using multipart/form-data request. After utilizing the package from https://github.com/goodatlas/react-native-audio-record, I was a ...

Invoke a React component within a conditional statement

There is a function for exporting data in either csv or xls format based on an argument specifying the type. The functionality works flawlessly for xls but encounters issues with csv. Here's the code snippet: const exportFile = (exportType) => { ...

The functionality of min-height in CSS seems to be malfunctioning

One of my HTML elements has a parent with the ID #out, and a child with the ID #in. The parent is positioned absolutely, with a minimum height of 100%. It seems to be functioning correctly in most browsers, except when I also set the child's min-heigh ...

Having trouble connecting my CSS Bootstrap file in VS Code

Having trouble linking my bootstrap file to my HTML in VS Code. Despite successfully adding the link, it does not seem to be working. https://i.sstatic.net/Yt7VH.jpg ...

Can Facebox's settings be adjusted during runtime? If so, how can this be done?

Can Facebox settings be accessed and customized? For instance, I am interested in setting the location of the loading image dynamically as shown on line 4: <script type="text/javascript" src="<?php echo base_url(); ?>media/facebox/facebox.js" > ...

Incorporating Anchors for Seamless Navigation in Menus

My website has various sections on the homepage and I want to add an anchor link to the navigation. This will allow users to scroll down to a specific section, like "About Us," when clicking on the appropriate nav link. I also need the anchor link to work ...

Transform basic list into a two-dimensional array (grid)

Picture a scenario where we have an array: A = Array(1, 2, 3, 4, 5, 6, 7, 8, 9); We aim to transform it into a 2-dimensional array (a matrix of N x M), similar to this representation: A = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9)); It's ...

Utilize JavaScript and PHP to input data into a database

Trying to extract info from an HTML table based on checked checkboxes. function updateBasket() { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code f ...

Using copyTextureToTexture in three.js creates unsightly aliasing artifacts

Whenever I attempt to use the copyTextureToTexture function to copy texture1 (which contains a loaded image) to texture2 (a datatexture that was created with the same dimensions and format), I encounter severe aliasing artifacts. It seems like most of the ...