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

Show or hide a div based on the visibility of another div in Angular using *ngIf

Looking for a way to dynamically display images based on the visibility of another image? Consider the code snippet below: <div *ngFor="let badge of user.progress.unlockedBadges"> <img id="{{i}}_unlockedImage" *ngIf="badge == achievemen ...

Is there a way to adjust only the height of a responsive image?

Increasing the Height of an Image on a Mobile Device! I have an image that displays as the header of my website. When I resize the window to mobile format, the image resizes too. However, I want the height of the header image to be longer! Is this possibl ...

Interactive Javascript Dropdown Selection

I'm currently developing a registration page for a website and I've added a drop-down box that explains to users why we need their birthday. However, I seem to be having issues with my code. Take a look at the script below: <script language=& ...

Utilize Electron to extract and render content from a local file into HTML code

I am struggling to find a solution for automatically reading and parsing a local csv file in an electron application. When I use 'fs' to open the file, I can't figure out how to pass the contents into the HTML window. One option is to use a ...

Position the Bootstrap button on the right side

this is the code I am working with: <p class="h1 p-3 mb-2 bg-danger text-white text-danger">Lagerbestand unter Mindestmenge! </p> <br /> <div class="border text-center"> <p class="h5 text-center">Durc ...

Component built in ReactJS for file uploads to a server running on Spring MVC/Data-REST

For quite some time, I have been on the lookout for a ReactJS component that enables file uploading from a browser, with the ability to save it to the server where the ReactJS application is deployed. I've come across several components that facilita ...

Send a basic variable from jQuery using Ajax to Ruby

I'm a beginner in the world of Ruby, jQ, and Ajax. I always make sure to do some reading before reaching out for help. My issue is with sending a basic jQuery variable to a Ruby controller using Ajax for a seamless transition. Is it possible to pass ...

What is the method for accessing 'this' beyond the scope of my object?

My Jcrop initialization for a website includes my own namespace. I have a question regarding the this keyword. Whenever I need to access my base object called "aps" in any callback function, I have to wrap this in a variable (I chose the word that). Is t ...

Capturing jQuery ajax requests in Angular

Within my Angular application, I am utilizing the integrated $.couch API from CouchDB. My goal is to intercept every ajax request, regardless of whether it originates from Angular's $http service or jQuery's $.ajax (which is utilized by $.couch). ...

The importance of incorporating React into the scope of functional component development

While discussing class components, it's clear that they are part of the global React object. But why is it necessary to import them with every functional component? And do bundlers play a role in this requirement? I've been coding for 5 months n ...

Positioning bar chart columns and text using CSS

My component generates HTML for a simple bar chart, with the height and background color computed within the component. Everything functions correctly, but I am facing an issue where long text causes displacement of the bar above it. Another problem is th ...

Discover the secret to automatically calling a function every minute when the page is loaded!

Our team is currently developing a PhoneGap application with 4 pages. We are in need of posting the current latitude and longitude every minute to our server. Fortunately, we are familiar with how to post values to the server as well as how to retrieve the ...

React state is not refreshing as expected

I am having trouble updating the state with new employee data. The push function is not inserting the new employee data into the state. In the addPar function, I set up a console log and it shows that the data is there, but it fails to push it to the sta ...

Ways to eliminate unnecessary items from a JavaScript object array and generate a fresh array

My JavaScript object array contains the following attributes: [ { active: true conditionText: "Really try not to die. We cannot afford to lose people" conditionType: "CONDITION" id: 12 identifier: "A1" ...

Looking for someone to break down this Typescript code snippet for me

As a Javascript developer, I am currently diving into an unfamiliar TypeScript code block within a project. Here is the code snippet: ViewModel newPropertyAddress = new ViewModel(){name, previousPro = oldValue } ...

Extract information from a JSON string and present it on the screen

I am a complete novice when it comes to D3 (with very little experience in JS). Here are the lines of code I am working with: <script type='text/javascript'> data ='{"mpg":21,"cyl":6,"disp":160,"hp":110,"drat":3.9,"wt":2.62,"qsec":16. ...

I am unable to see the text field when I use element.text. What could be the reason for this

As I work on collecting online reviews using Selenium Chrome Webdriver, I've encountered a challenge with TripAdvisor. The reviews are truncated and require clicking a "More" button to view the complete text. Within the html code, there is a class cal ...

Tips for accessing payment details from a stripe paymentElement component in a React application

Here is a basic code snippet for setting up recurring payments in Stripe: await stripe ?.confirmSetup({ elements, confirmParams: { return_url: url, }, }) After browsing through the documentation and the internet, I have two unanswere ...

When the specified condition is met in HTML along with a designated URL

Is there a way I can implement an if condition in my HTML file within Codeigniter that checks the URL? Depending on whether or not it contains part of the URL, it would perform different actions. For instance: The initial URL is localhost/index.php/ca ...

How can I make my JQuery datatable span the full width of the screen, regardless of the resolution?

In my Rails application, I am using JQuery Datatable with the following code: <%= content_tag :table, role: :my_datatable, id: 'my_datatable', style: 'height:500px; overflow-y: auto;&apo ...