How can I use Jquery to alter the background color of alternating divs with zebra stripes?

I am working with a list of divs that have zebra striping in CSS, where the odd divs have a light grey background. My goal is to change the background color of a clicked div to blue. However, I have encountered an issue where this only works for even divs, possibly due to the zebra striping having a higher specificity than the class added with addClass. Rearranging the selectors in my CSS file has not resolved the problem.

div.row div:nth-child(odd) {
  background-color: #fafafa;
}

.selectedRow {
    background-color: #338FFF;
}

$('.js-div').on('click', function (e) {
  $(e.toElement).addClass('selected_color');
}

Answer ā„–1

To enhance the styling of your odd rows, create a more specified .selectedRow class in your css:

.selectedRow,
div.row div.selectedRow:nth-child(odd) {
    background-color: #338FFF;
}

See it in action: http://jsfiddle.net/xyz123abc/1/

Answer ā„–2

You have mistakenly referenced the wrong class in the click function. The reason it is only affecting even rows is because the stylings for nth-child(odd) are taking precedence over the selectedRow class.

$('.js-div').click(function(e) {
  if(!$(this).hasClass('selectedRow')) {
      $(this).addClass('selectedRow')
      $(this).css('background-color', '#338FFF');
  } else {
      $(this).removeClass('selectedRow')
      $(this).removeAttr('style');
  }
})
.js-div {
    width:100%;
    height:40px;
}

div.row div:nth-child(odd) {
  background-color: #fafafa;
}

.selectedRow {
    
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
    <div class="js-div"></div>
    <div class="js-div"></div>
    <div class="js-div"></div>
    <div class="js-div"></div>
    <div class="js-div"></div>
    <div class="js-div"></div>
    <div class="js-div"></div>
    <div class="js-div"></div>
    <div class="js-div"></div>
    <div class="js-div"></div>
</div>

edit: Included an alternative approach since !important cannot be used.

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

Tips for aligning text to match the starting point of other text

Currently, the text appears as follows: Lorem ipsum dolor sit amet consectetur adipiscing elit vitae orci elementum dictum I want it to look like this: Lorem ipsum dolor sit amet consectetur adipiscing elit vitae orci elementum dictum I ...

Guide to rendering a dynamic Thymeleaf tag retrieved from the backend

Is there a method to display Thymeleaf tags that are received from the back-end? For example, I have a JSON object called textObj as shown below coming from the back-end. textObj.json { "title" : "Page Title", "text" : "blah blah blah blah <div th: ...

Is there a way to inspect the outcome of a jQuery post for a specific outcome?

I need to send a value to another page and display results from a SQL query in an overlay only if there are results. Otherwise, I do not want the overlay to appear. Currently, the overlay pops up regardless of whether there are results or not. I am new to ...

Tips for aligning the first row of a table with a line of text

I need assistance aligning the first row of a table with a line of text. Specifically, I am trying to achieve ** some text ** |first row of table      |             ...

Utilizing SASS to retrieve the H, S, L values from a color

Is there a way to extract the H, S, L values from a hex color in SASS and assign them to separate CSS variables? $colors: ( "primary": $primary, "secondary": $secondary) !default; :root { @each $color, $value in $colors { -- ...

If Bootstrap CSS is linked, custom CSS style rules will only take effect when added within a style tag

Iā€™m currently facing an issue where my custom CSS rules are not being applied after linking Bootstrap in my project. I am using Bootstrap CSS for a custom layout and need to incorporate my own styling as well. When I link bootstrap.min.css followed by m ...

Tips for implementing a for loop within a Bootstrap-Popover using JavaScript

After spending several days searching for a suitable example to no avail, I decided to bring my specific use case to SO. I currently have three Bootstrap 5 cards. https://i.sstatic.net/zDVOF.png I am looking to create Popovers for each card, with the po ...

Guide on Enabling Pagination for Swiper Slider on Mouse Hover

var thumbSlider = new Swiper('.slider .slider-thumbs', { slidesPerView: 'auto', }); var contentSlider = new Swiper('.slider .slider-content', { disableOnInteraction: false, ...

Using JQuery to automatically click a button every 2 seconds

Currently, there is a refresh button that triggers a web service call to fetch new data and updates a div container. However, I am looking for a way to automatically update the div container without requiring user interaction. Is it possible to use jQuery ...

Exclude a Child with jQuery Selector

Is there a way to select the entire body excluding just one element? $("body").not('#to-exclude').mouseup(function(){ // ... }); This approach is not effective. ...

"The Jquery Ajax Each function is designed to give back twice as much

I am currently facing an issue with a Jquery Function that is responsible for fetching a list of users from the database and displaying their information in div elements. The problem I am encountering is that I am getting duplicate results. This is my firs ...

Troubleshooting jQuery and Mootools compatibility problem in Internet Explorer 8

I am currently working on a webpage that is using both Mootools 1.4 and jQuery 1.5.1 at the same time. I understand that this setup is not ideal, but for various reasons, I have no choice in the matter. Most browsers display the page without any issues, ho ...

Whenever an Ajax POST request is sent to a Cakephp Controller, it consistently returns an empty

I am facing a challenge in retrieving the POST value in the controller as I am relatively new to this. It feels like I have been in the dark for too long and could really use some guidance. I have checkboxes in my application and need to pass the IDs of t ...

Failure to display alert pop-up

I'm having trouble with my code. The button appears, but the alert message doesn't show up when I click on it. What mistake am I making? <DOCTYPE! html> <html> <body> <h1>Trying out JavaScript</h1> <button> ...

Images on NextJS are failing to resize properly in Next 13

I have been facing challenges with optimizing image sizes for different screen resolutions using the NextJS Image component. Currently, all images seem to be loading at their largest size on various screens. Below is a screenshot showing the resolution t ...

The functionality of Jquery datatables seems to be faulty when navigating to the second page

While utilizing the jQuery datatables plugin, I encountered an issue where the event click function only worked on the first page and not on subsequent pages. To address this problem, I discovered a helpful resource at https://datatables.net/faqs/ Q. My ...

Switch the modal trigger from clicking to loading with a delay in time

I have been experimenting with a simple modal plugin that I downloaded and modified to better understand its functionality. One thing I am curious about is how to change the trigger from an 'on click' event to an 'on load' event with a ...

Guide on breaking up a string into separate lines

Can someone help me with separating the strings in this line "Add Problem Report \n Add Maintenance Report \n Add Expenses Report \n Add Contract", into new lines? I have tried using br, pre, and \n but it does not seem to work. HTML ...

Display an image overlaying a div

I am attempting to position an image outside of its parent div in such a way that it appears to be sitting on top of the div without affecting the height of the parent. However, no matter what I attempt, the image consistently gets clipped by the parent di ...

What steps can I take to fix the Error with webpack's style hot loader JavaScript?

Just starting out with native script and encountered an issue when running this code: <template> <view class="container"> <text class="text-color-primary">My Vue Native Apps</text> </view> </template> &l ...