rhill45
rhill45

Reputation: 569

JS code to check a date, highlight the element containing that date if it meets condition

I am learning js. I am looking for a relatively simple script that would check a date within an element that is formatted as HTML text and always in the arrangement mm/dd eg today's date is 01/12. There are multiple elements like this on the page, all have a different date:All are in this format:

<td width="91" valign="middle" class="sem-date"><p align="center">03/27</p></td>

The script should:

1.read all elements on page when page opens that contain .sem-date.

2.set up a condition, where if today's date is the date in the element, or 5 days previous, set to true. Otherwise set to false.

3.if true than highlight element by inserting into the element. If false do nothing.

so, if true the above element would be changed to:

<td width="91" valign="middle" class="sem-date" style="background-color: #FFFF00"><p align="center">03/27</p></td>

I was wondering if anyone had small script to accomplish this or could assist me in getting started.

Upvotes: 0

Views: 66

Answers (1)

Roberto Linares
Roberto Linares

Reputation: 2225

For the elements selection, check for the Document.getElementsByClassName documentation. That's a pure javascript solution but if you need to do it in older browsers, try with jQuery's class selector.

After you get the list of elements with that class, you can use a traditional for, a native foreach function or jQuery's foreach (again, considering older browsers).

To get the HTML value of an element, use the innerHTML attribute.

For the Date comparison, get the day/month values with a split over the slash character. and compare its fields manually with the day and month fields in a new Date object.

Finally, to change an element's style, use the style attribute.

There can be other solutions to this problem but I think this is a common one.

Upvotes: 1

Related Questions