Add distinctive formatting for the final element that is not the last child

Presented with a fascinating challenge, I find myself with an ever-changing number of .child.red children. I am in need of referencing the last .child.red element dynamically using styles. Although I have attempted to achieve this on my own, I am curious about your approach: the last child. Intriguing. Appreciate any insight.

.child {
  background: blue;
}
.child.red:first-child {
  background: red;
}
.child.red:last-child {
  background: red;
}
<div class="parent">
  <div class="child red">
    1
  </div>
  <div class="child red">
    2
  </div>
  <div class="child red">
    3
  </div>
  <div class="child red">
    4
  </div>
  <div class="child">
    5
  </div>
  <div class="child">
    6
  </div>
  <div class="child">
    7
  </div>
</div>

<!-- begin snippet: js hide: false console: true babel: false -->

//// css

Answer №1

To achieve the desired result, you have two options: either add a class to the last child element with the "red" class and style it using CSS, or use JavaScript to target the last child with the "red" class and add a new class dynamically.

Here is an example of a JavaScript solution:

var redElements = document.querySelectorAll(".red");
var lastRedElement = redElements[redElements.length -1];
lastRedElement.classList.add("last");
.child {
  background: blue;
}
.child.red:first-child {
  background: red;
}
.child.red.last {
  background: red;
}
<div class="parent">
  <div class="child red">
    1
  </div>
  <div class="child red">
    2
  </div>
  <div class="child red">
    3
  </div>
  <div class="child red">
    4
  </div>
  <div class="child">
    5
  </div>
  <div class="child">
    6
  </div>
  <div class="child">
    7
  </div>
</div>

<!-- begin snippet: js hide: false console: true babel: false -->

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

Is there a way to enable scrolling on a page without editing the HTML? I have a table inside a div that is overflowing, and I want the page to scroll,

I'm facing an issue with a DIV that is 600px wide and contains a table. Due to long email addresses, the wrapping isn't working properly even after using word-wrap: break-word. I've experimented with changing the width, adding !important, a ...

Avoid data duplication or triplication by implementing a pop-up loop when adding new information

Seeking assistance in identifying the line of code that is causing data duplication or triplication when adding information in a pop-up form. The New/Update/Delete functions are functioning correctly, except for the Add function. The problem arises when i ...

Invoke functions within a separate function

I am facing an issue when it comes to invoking functions within another function. Below is a snippet of the code I am working with: <script> function saveInfo() { function returnEmail() { var _e = document.getElementById("em ...

The URL routing in Vue-router seems to be incorrect as it directs to the wrong page. To fix this issue, make sure to include a '#' before the

Welcome to my website! Check out my home page here: https://i.sstatic.net/znfq0.jpg If you're interested in reading my blog, visit the blog page here: https://i.sstatic.net/oiYSY.png I've built this site using vue3. Here's a snippet of th ...

The hover feature on my website is making the picture flicker

I am experiencing an issue with a map on my website that contains four colored squares. When I hover over one of the squares, the image of the map changes to show the route corresponding to that color. However, this causes the image to shift position and i ...

"Clicking on the 'View More' button within a foreach loop is only functional for the

I am trying to iterate through a list of items using a foreach loop, and each item has a "view more" option. The intention is that when I click on this option, it should expand to show more details about the respective item. However, I am encountering an i ...

What could be causing the dysfunction of the jQuery class adding function?

I'm new to using jQuery and I'm trying to add a class to the 'a' tag when the 'li' tag is clicked. However, it doesn't seem to be working as expected. $('.nav-item').click( function() { $(".nav-item a").re ...

Flask-SocketIO: Transmitting data between nodes using Redis adapter

When integrating SocketIO into an application running behind a node-balancer, the documentation recommends using SocketIO-Redis to facilitate event passing between nodes: const io = require('socket.io')(3000); const redis = require('socket.i ...

Separate modules in the Webpack.mix.js file don't produce any output files in the public folder

I've recently been tackling a Laravel project with an extensive webpack.mix.js file residing in the root directory, boasting nearly 5000 lines of code. In an effort to enhance organization and maintainability, I've opted to break it down into ind ...

What is the best way to restrict the selection of specific days of the week on an HTML form date input using a combination of JavaScript, React, and HTML?

I need help customizing my Forms Date Input to only allow selection of Thursdays, Fridays, and Saturdays. I've searched for a solution but haven't been successful so far. Is there any JavaScript or HTML code that can help me achieve this? Below ...

Can someone explain how to use JavaScript to make table data fill the entire row in a table?

After clicking the button, the layout of the table changes. I want to keep the original table layout even after the JavaScript function runs. I am still learning about JavaScript. function toggle(button) { if(document.getElementById("1").value=="Show ...

ReactJS bug: Array rendering problem affected by recent changes

Why does ReactJS remove the first element instead of the middle element when using array.splice to remove an element from an array? This is my code. I am using Redux as well. const reducerNotesAndLogin = (state = initialState, action) => { var tableNo ...

Ways to troubleshoot and verify values in PHP that are sent through AJAX

In my jQuery function, I am using AJAX to send values to a PHP file: $.ajax({ //make ajax request to cart_process.php url: "cart_process.php", type: "POST", dataType: "json", //expect json value from server data: { quantity: iqty, ...

Error message: The AJAX POST request using jQuery did not return the expected data, as the data variable could not be

There is a script in place that retrieves the input text field from a div container named protectivepanel. An ajax post call is made to check this text field in the backend. If the correct password is entered, another div container panel is revealed. < ...

Struggling to grasp the concept of async/await and promises

I'm fairly new to working with node.js and JavaScript in general. I've been trying to understand promises and async/await concepts, specifically in the context of requesting images from a remote URL asynchronously and converting them to base64 fo ...

"Experimenting with KinectJS: Adding Rotation to a Pair of Images

Looking for a solution to rotate both the upper arm and forearm images simultaneously? The upper arm rotates around a specific point, and the forearm also rotates around this same point. How can I make sure that the forearm rotates when the upper arm does ...

Italian calendar conversion for the react-multi-date-picker library

I recently integrated the react-multi-date-picker into my project, utilizing the multiple mode feature. However, I encountered an issue when trying to display the Italian calendar based on the language setting. Despite using locale="it", the calendar was n ...

Aligning multiple spans vertically within a div of varying height (ui-select-multiple)

I am currently using AngularJS ui-select's Multiselect feature. If you want to see how my multiselect looks, check it out here: http://plnkr.co/edit/zJRUW8STsGlrJ38iVwhI?p=preview When arranging spans in multiple lines, achieving nice vertical align ...

Merge different $_GET parameters together before submitting

Not too certain if it's achievable, but here's the issue I'm struggling with. I need a form that generates this specific link. The desired end link is: I am unable to utilize a form for this task, but I can work with input fields. Any sug ...

jquery monitors an element to see if it contains a particular attribute, then takes action accordingly

I'm attempting to conceal a div when an anchor tag (a) has a particular href, and reveal it when the href is different. This is what I've tried: if($('a[href="#intro"]').not(".active")) { $('.navbar-brand').hide();} else ...