Adding dynamic colors to nested and sibling divs with a specific class

I am facing an issue with applying alternating colors to nested divs. The challenge is that these divs are not always siblings within the list items.

Here is the HTML structure:

<ul>
    <li>
        <div class="R">Bat</div>
        <div class="R">description</div>
    </li>
    <li>
        <div class="R">Cat</div>
    </li>
    <li>
        <div class="R">Rat</div>
        <ul>
            <li>
                <div class="R">one
                    <div class="R">blah</div>
                    <div class="R">blah blah</div>
                </div>
            </li>
            <li>
                <div class="R">two
                    <div>
            </li>
            <li>three</li>
        </ul>
    </li>
</ul>

This is how I want it to look (colors added with inline CSS):

<ul>
  <li>
    <div class="R" style="background-color:red;">Bat</div>
    <div class="R" style="background-color:green;">description</div>
  </li>
  <li>
    <div class="R" style="background-color:red;">Cat</div>
  </li>
  <li>
    <div class="R" style="background-color:green;">Rat</div>
    <ul>
      <li>
        <div class="R" style="background-color:red;">one
          <div class="R" style="background-color:green;">blah</div>
          <div class="R" style="background-color:red;">blah blah</div>
        </div>
      </li>
      <li>
        <div class="R" style="background-color:green;">two
          <div>
      </li>

    </ul>
  </li>
</ul>

Answer №1

Here's a suggestion: utilize the jQuery selectors :odd and :even to target odd and even divs and assign background colors accordingly. Take a look at the code snippet below:

$(function() {
  $('ul div.R:odd').addClass('oddColor');
  $('ul div.R:even').addClass('evenColor');

});
.oddColor {
  background-color: red;
}
.evenColor {
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul>
  <li>
    <div class="R">Bat</div>
    <div class="R">description</div>
  </li>
  <li>
    <div class="R">Cat</div>
  </li>
  <li>
    <div class="R">Rat</div>
    <ul>
      <li>
        <div class="R">one
          <div class="R">blah</div>
          <div class="R">blah blah</div>
        </div>
      </li>
      <li>
        <div class="R">two
          <div>
      </li>
      <li>three</li>
    </ul>
  </li>
</ul>

Answer №2

$(document).ready(function() {
  $(".R:even").css("background-color", "green");
  $(".R:odd").css("background-color", "red");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
  <li>
    <div class="R">Bat</div>
    <div class="R">description</div>
  </li>
  <li>
    <div class="R">Cat</div>
  </li>
  <li>
    <div class="R">Rat</div>
    <ul>
      <li>
        <div class="R">one
          <div class="R">blah</div>
          <div class="R">blah blah</div>
        </div>
      </li>
      <li>
        <div class="R">two</div>
      </li>
      <li>Three</li>
    </ul>
  </li>
</ul>

$(function() {
  $('ul div.R:odd').addClass('oddRow');
  $('ul div.R:even').addClass('evenRow');
});
.oddRow {
  background-color: red;
}
.evenRow {
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
  <li>
    <div class="R">Bat</div>
    <div class="R">description</div>
  </li>
  <li>
    <div class="R">Cat</div>
  </li>
  <li>
    <div class="R">Rat</div>
    <ul>
      <li>
        <div class="R">one
          <div class="R">blah</div>
          <div class="R">blah blah</div>
        </div>
      </li>
      <li>
        <div class="R">two</div>
      </li>
      <li>Three</li>
    </ul>
  </li>
</ul>

Answer №3

$('div.R').each(function(index) {
  $(this).css('background-color', index % 2 === 0 ? '#cc0' : '#0cc');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<ul>
  <li>
    <div class="R">Dog</div>
    <div class="R">description</div>
  </li>
  <li>
    <div class="R">Frog</div>
  </li>
  <li>
    <div class="R">Pig</div>
    <ul>
      <li>
        <div class="R">one
          <div class="R">oink</div>
          <div class="R">squeal</div>
        </div>
      </li>
      <li>
        <div class="R">two</div>
      </li>
      <li>three</li>
    </ul>
  </li>
</ul>

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

The method for connecting the width of a panel to the height of the viewport in Ext Js

I'm looking to automate the adjustment of a panel's height based on the viewport's height using Ext js. Although achievable using listeners, I believe utilizing Ext js variable binding would be more efficient. However, I've encountered ...

Tips for debugging a jQuery POST AJAX operation

I am struggling with getting the data from the server to display properly in the <div id="demo"> element. Sometimes, the data appears briefly and then disappears, while other times, it simply does not show up at all. I have tried various solutions a ...

"Dealing with an array of routes in AngularJS $

Clicking on the Home link triggers the goTo function, but it redirects to a blank page as shown: https://i.sstatic.net/qerBI.png Upon clicking on the browser's back button, it redirects to the desired page (firstPage). https://i.sstatic.net/oaANp.p ...

Angular: Experiencing difficulty in locating the position of an element within an array

I am facing an issue with the structure of my controller. Here is how it currently looks: MyControllers.controller('ContentCtrl', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) { $htt ...

Panel of expandable content

Hello everyone, I am new to jQuery UI and I have a question about the accordion API. I read through the accordion documentation. However, it doesn't provide much information on what can be used as the content panel. Based on my tests, I discovered ...

Simple steps to turn off error highlighting for TypeScript code in Visual Studio Code

Hey there! I've encountered an issue with vscode where it highlights valid code in red when using the union operator '??' or optional chaining '?.'. The code still builds without errors, but vscode displays a hover error message st ...

Having an issue with the 'scroll' event not being disabled in jQuery

Currently, we are encountering an issue with the implementation of a simple hiding menu when scrolling and showing it back once the user stops scrolling. The method .on('scroll') works as expected, but .off('scroll') is not functioning ...

What is the best way to create a horizontal line above a div to serve as a home bar?

.topbar { background-color: white; position: fixed; margin: -10%; z-index: 10; height: 10%; width: 110%; } I have created this code for a div element, intending it to serve as a navigation bar on my website. My goal is to include an orange line at the top ...

Tips for eliminating space between .dropdown and .dropdown-menu

While in mobile view and clicking on the .dropdown menu, there appears to be a slight space between the .dropdown and the .dropdown-menu. This issue is highlighted here: https://i.sstatic.net/vJ2Sd.png Question: Is it possible to eliminate that small ...

Tips for creating retryable AWS S3 requests

Whenever I attempt to download multiple files from an S3 bucket using the Node SDK, sometimes one of the requests times out. Instead of giving up, I'd like the request to automatically retry for a successful download. The JSON error response states t ...

Incorporate an external website into HTML5 code

I have a dilemma with embedding one website into another. I am currently utilizing embed code for this purpose. <object data="http://mywebsite.com" width="100%" height="100%"> <embed src="http://mywebsite.com" width="100%" height="100%"> ...

Adjusting the font size results in a shift in the margin and padding

I am currently designing the homepage for my website. I want all the text to be aligned on the same line, but whenever I increase the font size of one element, it creates space around it, shifting it slightly to the right and pushing the text below down. ...

Is it possible to alter Bulma Sass variables dynamically by referencing the class of an HTML element?

I am currently working on implementing a dark and light theme using bulma. My plan is to dynamically assign classes to elements using vue (such as .dark-theme or .light-theme) and then apply different colors based on these themes. However, I am facing an i ...

Tips for displaying specific elements from an array by their ID when a button is clicked

I am facing an issue and need some help with my code structure. Below is the array I am working with: const countries = [ { id: 1, props: { url: '/images/polska.jpg', title: 'Polska', width: width, ...

What is the best way to append data to the end of an object using ReactJS Hooks?

Looking to set up a checkbox page in ReactJS where data is filtered by checkboxes from different categories using ReactJS hooks. Currently, I am storing the selected checkboxes as an object: { color: 'orange', shape: 'square' } ...

Mobile display trapping Bootstrap navbar

Can anyone help me figure out why my navbar is stuck in its mobile display? Here is the link to the code: http://jsfiddle.net/enL35t1q/ Navbar <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul cla ...

Identify HTML elements by their tag name and position using the

Can someone help me extract the text from only the second li element using look_down? Any guidance would be appreciated :) <ul class="threads"> <li>one</li> <li>two</li> <li>three</li> </ul> < ...

Ways to enhance the functionality of an input component

Within my React app, I have an input component that triggers an onChange event when connected to another component: <input type="text" onChange={onChange} /> Now, I am looking to enhance this input component by incorporating a prop from another com ...

Incorporating a vertical slider alongside a fullPage.js section for a dynamic user experience

Is there a way to achieve a transition effect similar to this example for fullPage.js section-elements? <div id="fullpage"> <div class="section"></div> <div class="section"></div> </div> I have experimented with var ...

Problems arose when attempting to adjust the size of the container function

I've been working on a Joomla 2.5 template that consists of three main sections: top, container, and footer. While trying to set the "container" section to have a minimum height of 100%, I faced various challenges which led me to use jQuery for assist ...