Apply a class to each consecutive element following the current one until reaching a child element with a

My goal is to apply a "bg-info" class using jQuery to all rows (tr) that come after odd rows with a child element of "test". The "bg-info" class should be removed when a row with a child element of "test" is encountered, and then re-applied when the next odd row with a child element of "test" is seen. Since the number of rows can vary, the solution cannot rely on a fixed count of rows. Despite many attempts, I have been unable to get this functionality working correctly. Any help would be greatly appreciated. See JSFiddle for details :)

JSFiddle

https://jsfiddle.net/vrpuahue/4/

HTML

<table>
  <thead>
    <tr>
      <th>Test</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        <div class="test">Test1</div>
      </td>
    </tr>
    ...
  </tbody>
</table>

CSS

.bg-info {
  background: grey;
}

JS

$('tbody tr td .test:odd').parent().parent().addClass('bg-info');

Answer №1

If you're looking to target specific elements, the nextUntil method is a great tool.

You can easily differentiate between even and odd parents by adding classes and then apply styling to the desired elements using highlight.

Check out the demo here

$('.test:odd').parents('tr').addClass('odd');
$('.test:even').parents('tr').addClass('even');
$('.odd').nextUntil('.even').addClass('highlight');
.highlight {
  background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table>
  <thead>
<tr>
  <th>Test</th>
</tr>
  </thead>
  <tbody>
<tr>
  <td>
    <div class="test">Test1</div>
  </td>
</tr>
<tr>
  <td>Do Not Highlight</td>
</tr>
<tr>
  <td>Do Not Highlight</td>
</tr>
<tr>
  <td>Do Not Highlight</td>
</tr>
<tr>
  <td>
    <div class="test">Test2</div>
  </td>
</tr>
<tr>
  <td>Highlight</td>
</tr>
<tr>
  <td>Highlight</td>
</tr>
<tr>
  <td>Highlight</td>
</tr>
<tr>
  <td>
    <div class="test">Test3</div>
  </td>
</tr>
<tr>
  <td>Do Not Highlight</td>
</tr>
<tr>
  <td>Do Not Highlight</td>
</tr>
<tr>
  <td>Do Not Highlight</td>
</tr>
<tr>
  <td>
    <div class="test">Test4</div>
  </td>
</tr>
<tr>
  <td>Highlight</td>
</tr>
<tr>
  <td>Highlight</td>
</tr>
<tr>
  <td>Highlight</td>
</tr>
<tr>
  <td>
    <div class="test">Test5</div>
  </td>
</tr>
<tr>
  <td>Do Not Highlight</td>
</tr>
<tr>
  <td>Do Not Highlight</td>
</tr>
<tr>
  <td>Do Not Highlight</td>
</tr>
  </tbody>
</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

Execute iMacros Loop and terminate the process before proceeding to the next command

As a newcomer to the world of iMacro scripting, I am struggling with setting up a simple data scrape. I'm looking for guidance on how to create a loop for the following commands: URL GOTO=link1 URL GOTO=link2 URL GOTO=link3 WAIT SECONDS=7.5 Once th ...

How should h tags be correctly utilized?

Is it better to use h tags or lists to style content? Take a look at this code, is using h tags the appropriate choice here or should I consider using a list instead? <div class="col-xm-12 col-sm-6 col-md-4"> <h4>Get in touch< ...

gulp - synchronized gulp.pipe(gulp.dest) execution

Here's my challenge: I have two tasks, where Task B depends on Task A. In Task A, one of the requirements is to loop through an array and then use gulp.dest, but it seems like Task B will be executed before Task A is completed. The main goal of Task ...

Rails pagination will only show the link to the current page

Is there a way to show only the current page link with the << Previous link hidden when on the first page and next >> link hidden when on the last page? It should look like this: On the first page: 1 | next >> On the last page (with 4 pages): << ...

Why do I receive the error message "Error: Objects are not valid as a React child (found: [object Promise])" in NextJS13?

I'm feeling overwhelmed by this issue and unsure of how to resolve it. Here is the code that is causing trouble: 'use client' import React, { useState } from 'react' import AnimatedDiv from '../../../(shop)/(components)/animat ...

Switch to a different webpage based on radio button selections in a PHP script

On my webpage, I have two pictures that act as radio buttons, along with a "proceed" button. However, when I click on the button, it does not redirect to the desired page. Below is the code for my form and PHP processing page: <body> <fo ...

Exploring Zustand through Laravel validation errorsUnderstanding Zustand can be

I'm currently working on incorporating Zustand into my NextJS application. I have set up a Laravel endpoint for user login functionality. When there are validation errors, the endpoint sends back JSON in the following format: { "message" ...

Trigger an event, pause, and subsequently trigger another one within Vue

I have successfully emitted the following events to the parent component: this.$emit('sendToParent1', true); this.$emit('sendToParent2'); this.$emit('sendToParent3'); this.$emit('sendToParent4', true); this.$emit(&ap ...

Is there a way to pass locale data using props in VueJS Router?

To access hotel data, the URL path should be localhost:8080/hotel/:id (where id is equal to json.hoteID). For example, localhost:8080/hotel/101 This path should display the specific data for that hotel. In order to achieve this, we will utilize VueJS vu ...

Validating PHP code to ensure that either one of two form fields is filled in

I have been working on a website that utilizes javascript for various functions and PHP-based Captcha code to validate form fields. Everything is functioning well, but the form can still be submitted even if none of the fields are completed. I require at ...

Avoiding the default action to submit AJAX form data won't result in any changes to the front end?

Currently, I am working with Flask and have utilized JavaScript to prevent default behavior in order to send all the necessary data through an AJAX request. However, I am facing an issue where although my view contains all the data (verified by console out ...

Is there a way to create a JavaScript script that automatically updates a webpage for all users simultaneously?

I have developed a web application that enables users to modify content using JavaScript. Currently, these changes are only visible on the local browser and do not involve AJAX. However, I am wondering how I can ensure that these DOM alterations are refle ...

Will my JavaScript function be triggered when the page is resized while printing?

I have a simple HTML layout where I am using the TextFill jQuery library to automatically adjust the text size based on available space. Everything looks good on screen, but when printed, it seems like the page is resized and the JavaScript needs to be re ...

What is the best way to dynamically select and deselect radio buttons based on a list of values provided by the controller?

I am currently working on implementing an edit functionality. When the user initially selects a list of radio buttons during the create process, I store them in a table as a CSV string. Now, during the edit functionality, I retrieve this list as a CSV stri ...

Customize the Color of Your Material-UI Drawer

Need help with setting the background color of a Material-UI Drawer. I tried using the following code but it didn't work: const styles = { paper: { background: "blue" } } After defining the styles, I passed them to the Drawer component like ...

How can I prevent users from inputting negative numbers in a cellEditable material-table?

In my project, I am utilizing a material table with editable cells. I need to implement a restriction that prevents users from entering negative numbers in the field and displays an error validation message. How can I achieve this functionality? Check out ...

Adding dynamic HTML to the body in AngularJS based on URL alterations

I am currently developing a single-page application using Angular. I am trying to create a card stack made of divs, similar to this concept. https://i.stack.imgur.com/42M06.png The idea is that the app will have various URL links and a card should be app ...

Is it best practice to use the AngularFirestoreCollection for updating Firestore items in AngularFire?

Within my application, I have a list that necessitates the use of an "or" condition. However, according to the documentation: "In this case, you should create a separate query for each OR condition and merge the query results in your app." Consequently ...

Unable to render Material Icons on Vue/Quasar web app hosted on Azure

I am facing an issue with my webapp built using Vue and Quasar. I added the necessary icon imports to my quasar-user-options.js file. import '@quasar/extras/material-icons/material-icons.css' import "@quasar/extras/material-icons-outlined/ma ...

Unable to simultaneously execute TypeScript and nodemon

Currently, I am in the process of developing a RESTful API using Node.js, Express, and TypeScript. To facilitate this, I have already installed all the necessary dependencies, including nodemon. In my TypeScript configuration file, I made a modification to ...