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

Navigate through content to reach the bottom of the webpage

I am currently working on a layout that is similar to Facebook's messaging system (facebook.com/messages). I have made some progress with it, but not quite there yet. You can view my work so far here: https://jsfiddle.net/3nd0b17m/23/ The main issue ...

Tips for sending context in the success callback function of a jQuery AJAX request

const Box = function(){ this.parameters = {name:"rajakvk", year:2010}; Box.prototype.callJsp = function() { $.ajax({ type: "post", url: "some url", success: this.executeSuccess.bind(this), err ...

The minification of HTML scripts may cause problems with the <script> tag

Greetings! I have a PHP script that is used to minify the page by removing any comments or spaces. Here is the script: <?php function sanitize_output($buffer) { $search = array( '/\>[^\S ]+/s', '/[^&b ...

Removing the currently selected item from the OwlCarousel

I am trying to enable users to delete the item that is currently active or centered in an OwlCarousel. I have come across some code related to deleting items, but it seems to be a rare question: $(".owl-carousel").trigger('remove.owl.carous ...

excess margin running along the left side of each page

When visiting http://tadris3.ir/, one may notice a peculiar space on the left side of all pages. Can anyone assist in resolving this bothersome issue? ...

Can the serialization of AJAX URL parameters in jQuery be customized?

Is there a way to instruct jQuery or an AJAX call on how to format query string parameters other than writing a custom serializer? I am using a jQuery AJAX call and passing an object with URL parameters var params = {name: 'somename', favColors ...

Having a problem with Node.js and async.eachSeries? Want to figure out how to configure the callback function to generate a JSON file for each element in an array of

Currently, I am utilizing async.eachSeries to repeatedly call a function that generates an array called pointsForFormating. Each time this function is called, I format the pointsForFormating array and store the result in another array named pointsFormate ...

When using TouchableWithoutFeedback, I encountered the following error message: "Error: React.Children.only expected to receive a single React element child."

I am encountering the following issue: Error: React.Children.only expected to receive a single React element child. Whenever I incorporate the 'TouchableWithoutFeedback' component in my ReactNative project: return ( <TouchableWithoutFeed ...

What could be causing the form body to return null in a PUT request?

What could be causing the form data to not be stored in req.body? EJS/HTML <form onsubmit="EditJob()" class="editForm"> <div class="form-group-edit"> <label for="position">Position</label> <input type="pos ...

Is there a way to access an Excel file with JavaScript without relying on the ActiveX control?

Is there a way to access an Excel document using JavaScript code without relying on an ActiveX control object such as shown below: var myApp = new ActiveXObject("Excel.Application"); myApp.workbooks.open("test.xls"); ...

Can you explain the distinctions among “assert”, “expect”, and “should” in the Chai framework?

Can you explain the variations between assert, expect, and should? How do you know when to utilize each one? assert.equal(3, '3', '== turns values into strings'); var foo = 'bar'; expect(foo).to.equal('bar' ...

Manage the number of choices available on a drop-down selection form

I am working with a PHP variable $a of an integer type. Based on the value assigned to $a, I want certain options to be visible in a form. For example, if $a=1; then only the first two options should be displayed, and if $a=2; then the first three option ...

Framer motion layout animation fails to account for page scrolling during transitions in NextJs routes

Currently, I am working on a fascinating NextJS project that showcases a series of interactive blocks. As the user navigates through the app, these blocks dynamically adjust their size and position on the screen. To achieve this effect, I'm leveragin ...

Interacting with a Java String object using a JavaScript function

Currently, I am in the process of developing an Android application using Phonegap. My goal is to enable data sharing between my Java and JavaScript code. The user interface spans across different HTML and JavaScript pages, but there are specific strings t ...

Trouble with the Bootstrap navbar loading correctly

Recently I started using Bootstrap and decided to implement one of their templates. Everything is working fine, except for my navbar which is not loading correctly. It should look like this: Desired Navbar However, in both Chrome and Firefox, it appears l ...

What is the method to alter the fill of a circle using CSS when it is hovered over in JavaFX?

I am seeking assistance for a task involving a circle within an hBox. I would like the color of the circle to change when the mouse cursor hovers over it. Is there a way to accomplish this using JavaFX and CSS? If not, what is the recommended approach fo ...

Tips for saving the status of an accordion controlled by an angular directive

I am currently utilizing the accordion directive from angular-bootstrap. My goal is to save the is-open attribute of this accordion, so that when users navigate to another page on the website, the state of the accordion (i.e. is-open) remains unchanged. ...

How to Blend Pseudo-classes in CSS?

If I want the selected text in a link to turn red when hovered over, can I achieve that using the following CSS code? .abc:hover::selection {color: red;} Also, if I have the following link: <a href="123" class="abc">4567890</a ...

Steps to prevent user input on a textbox in asp.net that is associated with a date picker

Within my web application built with asp.net, I have a textbox with a connected date picker using jQuery. The goal is to disable the ability for users to manually enter text into the textbox. Instead, they should only be able to select a date from the da ...

Hover effect within nested CSS styling applied to the list item element

I have structured my HTML as follows: <div id="chromemenu" class="chromestyle"> <ul> <li><a rel="dropmenu1" href="#" class="">Buy</a></li> <li><a rel="dropmenu2" href="#" class="">Sell</a>< ...