Tips for adjusting the class of elements in neighboring rows of an HTML table with the help of jQuery's nextAll() selector

While attempting to switch classes using the jQuery selector .nextAll(':lt(3)'), I encountered an issue.

The class change does not take effect on new rows of HTML tables. It seems like the class change for the next 3 cells is only being applied by this method.

Is there a different approach to resolve this?

$(function() {
  $("td").click(function() {
    $('td').removeClass('outpatient'); //If you want to reset in each click
    $(this).nextAll(':lt(3)').addClass('outpatient');
  });
});
table td {
  width: 20px;
  overflow: hidden;
  display: inline-block;
  white-space: nowrap;
  border: 1px solid gray;
  text-align: center;
  padding: 5px;
  cursor: pointer;
}
.outpatient {
  background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</table>

Answer №1

Link to jQuery API Documentation about .nextAll()

Retrieve all subsequent siblings of each matched element, potentially filtered by a specified selector

As the next row is not a sibling of the td element, it is necessary to target the next row separately. One approach is to determine the number of elements selected by .nextAll() and highlight the remaining required elements in the next row.

$(function() {
  $("td").click(function() {
    $('td').removeClass('outpatient'); //If you want to reset in each click
    $(this).nextAll(':lt(3)').addClass('outpatient');
    
    fromNextRow = 3 - $(this).nextAll(':lt(3)').length;
    $(this).parent().next().children(':lt('+ fromNextRow +')').addClass('outpatient');
  });
});
table td {
  width: 20px;
  overflow: hidden;
  display: inline-block;
  white-space: nowrap;
  border: 1px solid gray;
  text-align: center;
  padding: 5px;
  cursor: pointer;
}
.outpatient {
  background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</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

Guide on creating a Discord bot that can delete its own message in a private message (DM) using Discord.js

Working on my Discord.js Discord bot, I'm exploring the option of having the bot delete its own message from a DM chat. Is it feasible to achieve this and if so, what code should I use? Attempting msg.delete() is throwing an error mentioning that this ...

The image will only display upon receiving a link, not a path

Having some trouble displaying an image on my website, despite having successfully done so in the past for other projects. The image is located in the same folder as my HTML file. Here's what I've tried: <img src="reddit.png"/> <img s ...

Tic-Tac-Toe: The square's value stays unchangeable

Currently, I am working on creating a tic-tac-toe game using pure vanilla Javascript, so I am aiming to keep it as simple as possible. I have run into an issue and need some guidance. The main requirement is that once a square has been clicked and filled ...

Maintain the expanded menu even after selecting a sub-item using jQuery

After conducting a thorough search, I was unable to find exactly what I needed. I have successfully implemented cookies on my menu so that when the page is reloaded, it remembers which menus were open. However, I noticed that clicking on a sub-item of Hy ...

Designing visual representations using the Canvas elementorGenerating graphic content

I want to design a creative text image where multiple characters come together to form a word, like "The Matrix", within an animated canvas with a matrix effect. The challenge I'm facing is figuring out how to display the text inside the canvas and th ...

Step-by-step guide on generating a downloadable file in Vue

As a beginner in Vue, I am tasked with downloading a file but unsure of how to proceed. My attempt at the code resulted in the image opening on a new page instead. <a class = "btn btn-success btn-xs" href = "https://78.media.tumblr.com/tumb ...

Sharing and displaying images on Sails JS platform

Using Sails JS, I am attempting to upload an image and display it in a view. Queries: The uploaded image is located in .tmp/uploads, how can I retrieve it from a view? Is there a method to access the uploaded image? The image's name is altered in ...

Vue.js 2 view failing to update after modifying data in Vuex state

Greetings, I am currently working on developing a table to monitor the validation status of multiple items. Below is the VueX store configuration: mutations: { ..., set_scaninfos: function (state, scaninfos) { Vue.set(state, 'scaninfos&a ...

Using jQuery, it is possible to eliminate a div element without affecting its contents

<div class="a"> <div class="b"> <ul> <li>Element A</li> <li>Element B</li> </ul> </div> </div> How can I eliminate div class="b" solely? I require the presence of div a, u ...

What is it about Next JS and React JS applications that causes them to use up so much cache?

"What causes Next.js and React.js applications to need a large cache, and how does this affect their performance and resource usage?" Refreshing constantly for even small changes in the application as a developer can be frustrating. Are there an ...

How can I enable pagination in Datatables when the table HTML is generated using Angular after the drawCallBack function?

Below is the drawCallBack function I have implemented: "fnDrawCallback": function( oSettings ) { console.log("dt redrawn"); var selector = $("#example_table"); console.log(selector); function recompileForAn ...

What could be the reason for the variable not resetting in my event handler?

Check out the code I've written below: $(document).ready(function () { var default_var = 2; var show_var = default_var; var total_var = 8; var increment_var = 2; var start_var = show_var+1; var end_var = show_var+increment_v ...

Displaying numerous information panels on Google Maps by extracting data from MySQL

Help needed! I've been struggling with this code for a while now. I can show multiple markers on the map but can't figure out how to display info details in a pop up box when they are clicked. Currently, I'm just trying to make it say "Hey!" ...

Is there a way to trigger a Modal to open upon clicking a custom-designed button in MaterialUI?

In my React and Material-UI project, I am attempting to trigger a Modal to open using a custom button. The button also performs other functions, which is why it's important for me to combine the "Modal Opening" action with these additional functionali ...

Tips for customizing the appearance of Material UI's time picker diolog styles

I am currently incorporating the Material UI Time Picker from GitHub, specifically TeamWertarbyte's repository. My task involves modifying the color of the time displayed. https://i.sstatic.net/3ezSY.png In the image provided, I aim to customize th ...

The issue with jQuery click function seems to be limited to Firefox

After a long hiatus from posting here, I hope this isn't breaking any rules. For those who prefer visual examples, you can visit the live page at: The drop-down menu functions perfectly in IE, Chrome, and Safari, but seems to be causing issues in Fir ...

Tips for resolving the UNABLE_TO_GET_ISSUER_CERT_LOCALLY issue while attempting to install Sentry using npm or curl

https://i.stack.imgur.com/G8hfZ.png curl -sL -k https://sentry.io/get-cli/ | bash Even though I've specified not to verify the certificate with -k, I'm still facing issues trying to install it. The script is supposed to automatically install sen ...

Tips for setting NgForm value within an Observable and verifying its successful implementation

Exploring the functionality of NgForm, I am testing to validate if the value of a form gets updated when the state of the store changes. @ViewChild('form') form: NgForm; ngOnInit() { this.subscription = this.store.select('shoppingList&apos ...

Is there a method available to define a custom auto-generated key when inserting an object into Firebase Realtime Database?

I've been working on pushing data to the firebase rtdb and I want to make sure I can easily access it from other places. Here's the code snippet that I'm using to add data to the rtdb: function addStudentHandler(studentData) { fetch( ...

How can I optimize Javascript and CSS that are being used on my website but are not physically hosted on my website?

On my website, I have a plugin called "Contact Us" that was created and is being operated by Dropifi. Lately, I've been working on optimizing my site for SEO/Speed using Google's PageSpeed Insights tool. I enabled compression with GZip for all el ...