Ways to extract information from the <td> tag

I'm not very knowledgeable about javascript, do you have any advice for me? I have a dynamically generated calendar and I would like to highlight the current day in "red". You can refer to my codepen for more details.

When I try to retrieve values from this table, I get an array that looks like this ~>

https://i.sstatic.net/BDhax.png

https://codepen.io/david_jons/pen/aPXeaK

<div id="calendar-container">
  <div id="calendar-header">
      <span id="calendar-month-year"></span>
  </div>
      <div id="calendar-dates">
  </div>
</div>

Javascript:

window.onload = function(){
    var d = new Date();
    var month_name = ['January','February','March','April','May','June','July','August','September','October','November','December'];
    var month = d.getMonth();
    var year = d.getFullYear();
    var first_date = month_name[month] + " " + 1 + " " + year;
    var tmp = new Date(first_date).toDateString();
    var first_day = tmp.substring(0, 3);
    var day_name = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
    var day_no = day_name.indexOf(first_day);
    var days = new Date(year, month+1, 0).getDate();
    var calendar = get_calendar(day_no, days);
    
    document.getElementById("calendar-month-year").innerHTML = month_name[month]+" "+year;
    document.getElementById("calendar-dates").appendChild(calendar);

    var tr = document.getElementById("calendar-dates");
    var tds = tr.getElementsByTagName("td");
    var current_date = d.getDate();
}

function get_calendar(day_no, days){
    var table = document.createElement('table');
    var tr = document.createElement('tr');
    
    //row for the day letters
    for(var c=0; c<=6; c++){
        var li = document.createElement('li');
        li.innerHTML = "SMTWTFS"[c];
        tr.appendChild(li);
    }
    table.appendChild(tr);
    
    //create 2nd row
    tr = document.createElement('tr');
    var c;
    for(c=0; c<=6; c++){
        if(c == day_no){
            break;
        }
        var td = document.createElement('td');
        td.innerHTML = "";
        tr.appendChild(td);
    }
    
    var count = 1;
    for(; c<=6; c++){
        var td = document.createElement('td');
        td.innerHTML = count;
        count++;
        tr.appendChild(td);
    }
    table.appendChild(tr);
    
    //rest of the date rows
    for(var r=3; r<=7; r++){
        tr = document.createElement('tr');
        for(var c=0; c<=6; c++){
            if(count > days){
                table.appendChild(tr);
                return table;
            }
            var td = document.createElement('td');
            td.innerHTML = count;
            count++;
            tr.appendChild(td);
        }
        table.appendChild(tr);
    }
    return table;
}

Answer №1

If you want to filter through an HTML collection, consider utilizing Array.prototype.filter with the HTML collection as the context.

Take a look at this example for guidance:

var items = document.getElementById("product-list").getElementsByTagName("li");
var target_item = "example";
var filteredItem = Array.prototype.filter.call(items, function(item) {
  return item.textContent.includes(target_item);
})[0];
filteredItem.style.fontWeight = 'bold';

Answer №2

To determine if the date you are inputting matches today's date, use the following function:

function checkIfToday(day, month, year){
  const today = new Date();
  return today.getDate() === day && today.getMonth() === month &&     today.getFullYear()===year;
}

Click here to try it out!

There are multiple ways to achieve this, and the above code is just one example.

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

The close() function in HTML <dialog> element has no effect

I have implemented a feature where confirmation <dialog>s are attached to forms that require them using the following code: const forms = document.querySelectorAll("form[data-confirm]"); forms.forEach((form) => { const confirm = docume ...

I am interested in incorporating pinia state management into my Vue 3 project

I'm currently working on implementing pinia state management in Vue 3, but I've encountered the following error: Module not found: Error: Can't resolve 'src/stores/cart' in 'C:\Users\Ali Haider\theme-project&b ...

The animation only applies to the initial item in ngRepeat

After implementing async data loading in my application, I noticed that NgRepeat only animates the first element in an array. Check out the example on jsFiddle Here is the HTML code snippet: <div ng-repeat="x in data"></div> And here is the ...

Error: The initial parameter must be a string, Buffer, ArrayBuffer, Array, or Array-like Object. An object type was passed in instead in CryptoJS

In my quest to encrypt and decrypt data in react-native, I embarked on using the crypto node module by incorporating it into my react native project through browserify. While attempting encryption with the code snippet provided below, an error surfaces sta ...

The issue with Nextjs getStaticPaths is that it is not retrieving data from Firebase Firestore

I'm encountering an issue with fetching dynamic data from firestore in nextjs using getStaticPaths. While rendering the data from firestore with getStaticProps works, I'm facing a problem when trying to access specific item details as it leads me ...

Organize data that is deeply nested

Struggling to normalize deeply nested API response data? Look no further than https://github.com/paularmstrong/normalizr. This tool can help simplify your data structure. For example, if your input data looks like this: const data = [{ id: 'compone ...

Creating an illuminated atmosphere: How to place a light source within a container using ThreeJS

Attempting to replicate the luminous box from Beat Saber in ThreeJS: https://i.sstatic.net/6IUmp.png Initiated by crafting a shape in Blender and exporting an OBJ. Imported it into Three, simply as geometry: https://i.sstatic.net/BGA1n.png Subsequently ...

Is there a way to replay a SWF movie when a jQuery button is clicked?

I designed a webpage using Dreamweaver that contains multiple SWF movies, each embedded within object tags like this: <object id="FlashID" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="160" height="600"> <param name="movie" valu ...

Requesting the user to repeatedly input their birth year until it is less than the current year

Can anyone help me figure out how to display a prompt until the user enters a birth year that is less than the current year? I've tried using a loop in my code, but I'm having trouble getting it right. Any assistance would be greatly appreciated. ...

The Express Electron framework does not support importing local JavaScript files

Despite my extensive search before flagging this as a duplicate, I have not been able to find the solution I need. I am encountering issues with using express and electron. Everything runs smoothly when I execute npm start (the start script in package.jso ...

Repeatedly copying data from one row to another in TypeScript

Within my React TypeScript component, I am working with an array of objects. Each row in the array contains a repeat button, and I am looking to create a function that will copy the data from the current row and paste it into all remaining rows. https://i. ...

The display/block feature will only function if the div element is contained within a table

I am facing an issue with hiding/showing two div elements alternatively. The code works perfectly when the divs are placed within a table, but fails when they are not in a table due to compatibility issues with Internet Explorer. I prefer not to use a tabl ...

Encountering an issue when bundling an application using electron-forge: "Unable to find solution for './→' "

Having trouble packaging my Electron application using electron-forge. It seems like the issue lies with native modules such as 'sqlite3'. Upon running the command npm run package, I encounter this error: Module not found: Error: Can't reso ...

Ways to launch numerous URLs in express.js

I am currently developing a service similar to a URL shortener. While a typical URL shortener redirects the user to one page, my service needs to open multiple URLs simultaneously. When a user clicks on a link from my website, I want it to open multiple l ...

Encountering a problem in custom functions.php - Array_slice() error message: parameter 1 must be an array

I am seeking assistance with an issue on our woocommerce store. We have custom functions.php code to display recently viewed products on a single product page, but the Apache Error Log is showing multiple errors. Here is the functions.php code: add_shortc ...

Tips for creating a universal settings storage class in Angular

I have implemented a new class as shown below. export class Configuration { public details: string = "xyz"; } Despite defining the class Configuration, I am facing issues when attempting to access the data field within it. The fields in which I attempt ...

Struggling to design a functional mobile keyboard

I've been working on creating a mobile keyboard, but I'm facing some issues with the JavaScript part. The problem seems to be in my code as the keyboard isn't responding when I try to type. Here's a snippet of the JavaScript I'm us ...

Retrieving data from the Vuex store in a Nuxt component

https://i.stack.imgur.com/htnuL.png Seeking guidance on passing a list of button names into a menu component from the Vuex store as per the instructions at https://nuxtjs.org/guide/vuex-store In my /store/store.js: export const state = () => ({ & ...

Is there a way to effortlessly append a slug to my URL in a Node.js platform?

Currently facing challenges with my templates. As I develop an e-commerce platform, I am using a json file containing product details to create cards for each product. Due to the large number of products, creating individual pages for each one is not feas ...

Unexpected patterns observed when utilizing parent/child routing files

I am working with a Node/Express backend that is implemented using TypeScript. Whenever I make changes to a file and save it, if I test the root route in Postman localhost:8000/, I receive the expected response. However, when I test localhost:8000/user af ...