Exploring ways to validate the existence of a class in HTML table elements

If I want to verify if each element has a specific class when creating tables and clicking on the corresponding cells above them,

This is what I have tried.

However, it did not work as expected.

How can I make this work correctly?

What am I missing here?

Thank you

$("td.number").click(function(){
  id=$(this).index();
  $("td.color").index(id).hasClass("aqua");
  });
td {
  transition-duration: 0.5s;
  border: solid black 1px;
  padding: 5px;
}

.number{
cursor:pointer;}

table {
  border-collapse: collapse;
}

.color{
 padding:5px;
 }
 
.aqua {
  background-color: aqua;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id=calendar></div>

<script>
let html = ''
html += '<table>';
let i = 0;

html += '<tr>';
for (let d = 0; d < 15; d++) {
  i = i + 1;
  html += '<td class="number">' + i +'</td>'
}
html += '</tr>';

for (let w = 0; w < 1; w++) {
  html += '<tr>';
  for (let d = 0; d < 15; d++) {
    html += '<td class="color"></td>'
    }
    html += '</tr>';
  }
html += '</table>'
document.querySelector('#calendar').innerHTML = html;

const arr = [1, 2, 10, 11, 14];

$("td.color")
  .filter(function() { return arr.includes($(this).index()+1); })
  .addClass('aqua');
</script>

Answer №1

.index() function returns the position as an integer, rather than finding an element based on its index - for that purpose, you should use .eq() method

Check out the updated fiddle:

$("td.number").click(function(){
  id=$(this).index();
  $(this).toggleClass("aqua", $("td.color").eq(id).hasClass("aqua"));
});
td {
  transition-duration: 0.5s;
  border: solid black 1px;
  padding: 5px;
}

.number{
cursor:pointer;}

table {
  border-collapse: collapse;
}

.color{
 padding:5px;
 }
 
.aqua {
  background-color: aqua;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id=calendar></div>

<script>
let html = ''
html += '<table>';
let i = 0;

html += '<tr>';
for (let d = 0; d < 15; d++) {
  i = i + 1;
  html += '<td class="number">' + i +'</td>'
}
html += '</tr>';

for (let w = 0; w < 1; w++) {
  html += '<tr>';
  for (let d = 0; d < 15; d++) {
    html += '<td class="color"></td>'
    }
    html += '</tr>';
  }
html += '</table>'
document.querySelector('#calendar').innerHTML = html;

const arr = [1, 2, 10, 11, 14];

$("td.color")
  .filter(function() { return arr.includes($(this).index()+1); })
  .addClass('aqua');
</script>

Answer №2

To target the specific element you're looking for, consider using the eq() method instead of index(). Here's an example:

$("td.number").click(function(){
  var id = $ (this).index();
  $("td.color").eq(id).hasClass("aqua");
});

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 background-size property fails to function properly on mobile devices

It's really puzzling why this issue is happening, perhaps it's due to my fatigue. The problem lies in the fact that the "background-size" property isn't functioning on my mobile devices; however, it works perfectly when I try to simulate it ...

Removing duplicate values in Vue after sorting

Explore <div v-for="todo in sortedArray"> <b-button block pill variant="outline-info" id="fetchButtonGap" v-model:value="todo.items[0].arrivalTime"> {{fromMilTime(todo.items[0].arrivalTime)}} < ...

Corrupting the structure of XML data

Utilizing a jQuery object to append elements and update the values of an XML document, initializing it with an XML string containing nodes like <tgroup>, <table>, <row>, <tbody>, etc. as shown below. var str = "<txml> <tab ...

Troubleshooting CSS Problems: Issues with background repeating and footer placement

I am currently in the process of transitioning my website to a CSS layout, and so far it's looking good. However, I am facing two specific issues with the page layout that I need help with: 1) The background image of the left-most column is not repea ...

Display the website logo when users share on WhatsApp

My goal is to have my website icon appear in WhatsApp when I share it (similar to the example below). https://i.stack.imgur.com/KCWi8.jpg I initially tried using this code, but it didn't work: <link rel="shortcut icon" href="css/img/favicon/favi ...

Utilizing CSS float with dynamic height

Is there a way to achieve height:auto; for a parent element even when child elements are using float:left; or float:right? Solution for the Parent Element: #parent { width:100px; height:auto; padding-bottom:10px; background:#0F0; ...

Tips for incorporating data attributes into <figure> elements and retrieving them using CSS

Can we enhance a <figure> element by adding data attributes and then utilizing them in CSS? For example, I attempted figure { margin: 0 attr(data-margin %); } using <figure data-margin="15">...</figure> but it didn't yield the d ...

use triple quotes for python variable declaration

I am looking to extract information from an HTML file that contains elements with the class name "link". My challenge is to read each line into a variable and then parse it, all while using triple quotation marks. How can I create a string variable that ad ...

Is it possible to post content and download at the same time with just one click

Is it possible to use AJAX to POST data and then trigger a download of the response when successful? Here is my current code: $(document).on("click", "#CSV", function () { var csv_value = $('#result').table2CSV({ delivery: 'va ...

Eliminating hyperlinks from web addresses

While browsing on both mobile and desktop, I encountered a problem with anchor tags. Whenever a link is clicked, the anchor id gets added to the URL, for example, www.mysite.com would become www.mysite.com/#anchor. This caused an issue when refreshing th ...

Learn the process of using AJAX to post JSON data to a server

I developed an application for Blackberry and successfully posted some data to the server. Now, as I am learning jQuery and jQuery Mobile, I want to achieve the same functionality of posting data to the server using jQuery. My UI is built in jQuery Mobile ...

Issue with Bootstrap navigation bar not displaying on iPad devices

Currently, I am working on creating a custom bootstrap menu that displays properly on an iPad screen size. I have implemented the standard navbar code from Bootstrap with a few tweaks. While it works well on smartphones and laptops, the issue arises when ...

Can data from an Angular app be accessed by an external JavaScript code within the same project?

I've been thinking about a theoretical scenario that luckily I haven't encountered yet. Imagine I have an Angular Project compiled in My PROJECT FOLDER. <br/> Inside this PROJECT FOLDER, there's another JAVASCRIPT FILE external to ...

Unable to proceed with entering subsequent values into the input field after the initial input in reactjs

Issue with login form: Unable to provide second value after entering the first one. The text input field does not allow for entering more than one value before completing the existing entry. import React, { useCallback } from 'react'; import { Te ...

Bring Component into Vue if necessary

I have multiple menu types and would like to determine which type of menu to use by configuring it in .env.local. For example: VUE_APP_MENU_TYPE=2 Here is the code snippet from my javascript file: let menu = false; if (process.env.VUE_APP_MENU_TYPE === &q ...

``The Dynamic Checkbox Selection Process using Ajax, Jquery, and PHP

I'm a bit confused about the next steps... <input id="" type="checkbox" name="" onClick="" /> <td> <h4>PDF Document</h4> <p> Do you have your own menu or flyer? You can add it to your App </p> ...

Lack of intellisense support for .ts files in Visual Studio Code

Currently, I am using Visual Studio Code 1.17.2 on Arch Linux to kickstart my work with Node.js/Angular4. To avoid confusion caused by loosely typed code, I have decided to switch to TypeScript for my NodeJS server as well. This is why my main file is name ...

Illustrating SVG links

I'm working on a basic svg animation project where I want to create a simple shape by animating a line under a menu link. The goal is to have a single line consisting of a total of 7 anchors, with the middle 3 anchors (each offset by 2) moving a few p ...

Pause for a moment before displaying the VueJS loading screen

When using VueJS, I have implemented a loader to be displayed on each route like this: router.beforeEach((to, from, next) => { store.commit('loading', true); next(); }) However, it seems unnecessary to show the loader for a request that ...

Retrieving information through SELECT with a post parameter

I have created the following HTML code: <select name="compet" id="compet"></select> <select name="spage" id="spage"> <option value="home">Home</option> <option value="insert">Insert</option> <option valu ...