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

Best practices for updating the value of a specific key within an object that contains recursion in JavaScript/TypeScript

I have a tree component that uses the following data structure type TreeNode = { id: string, parentId: string, renderer: () => React.ReactNode, expanded: boolean, children?: Array<TreeNode>, } Now, I am looking to add functionality for ...

Unable to view the image in browsers other than Internet Explorer

On a webpage, there is a feature where clicking on the "Add More" link should display an input box and a "Delete" button image. Surprisingly, this functionality works perfectly on IE browsers, but not on Mozilla or Chrome. In non-IE browsers, only the text ...

What is the best way to retrieve the values of "qty" and "price" and access them within the item [array] without knowing the IDs?

I am currently working on a shopping cart project, specifically on the "previous orders" page to display order details. My goal is to output this information in an (.ejs) file. The data structure includes nested objects, and within one object, propertie ...

The surprising way Next.js disabled the production build and transformed my rgba color into hsla

I created CSS code to display grid patterns like this: background-image { repeating-linear-gradient( 0deg, rgba(255, 255, 255, 0.43) 0px 1px, transparent 1px 20px ), repeating-linear-gradient( 90deg, rgba(255, 255, 255, 0.43) 0px 1px, transparent 1px 20 ...

Simple steps to access a feature on an AngularJS application

I have my angular application stored in a variable (initialized with:) var app = angular.module('app', [...]); Now, I need to access the $timeout service. How can I retrieve this service from it? I am looking for something like: var timeout ...

CSS to target every second visible tr element using the :nth-child(2n)

My table has a unique appearance (shown below) thanks to the application of CSS nth-child(2n). tr:nth-child(2n) {background-color: #f0f3f5;} I made some elements hidden on the vID, ID, and MO_Sub tr. <tr style="display:none"> The table's new ...

Widget remains static until job triggers data refresh, preventing CSS transition initialization

I am struggling with the html/coffee/scss aspects, although I'm comfortable with Ruby. On my website, I have implemented a hotlist widget sourced from this link: https://gist.github.com/andre-morassut/8705385. While it functions properly, I encounter ...

What sets @vue/cli-plugin-unit-jest apart from vue-jest?

Can you explain the distinction between these two software bundles? @angular/cli-plugin-unit-jasmine angular-jasmin If I already have one, is there a need for the other? And in what circumstances should each be utilized? ...

Utilize AngularJS to enable the forward and back buttons to fetch JSON data, but ensure that the data is only retrieved if the item meets

I have successfully implemented forward and back buttons for paging through data items in an array from a JSON file: Controller: dishControllers.controller('DrinkcardsController', ['$scope','$http','$routeParams', ...

Setting dynamic image dimensions within a div element

Is there a way to display the div width in percentage even when the image is not loaded? The image sizes are mentioned in percentage and they load dynamically, making it impossible to fix their size. How can we ensure that the div maintains the correct wid ...

How can we avoid multiple taps on Ext.Button in Sencha Touch?

Currently working on a Sencha Touch game, but struggling with users tapping buttons multiple times. Looking for a simple solution to prevent multiple tap events in the app.js file so that only one tap event is executed even if a user taps or presses for an ...

Exploring the World of Github on Windows: Understanding the 'master' and 'gh-pages' Branches

I have developed a simple jQuery plugin and uploaded it to Github. I am using both the Github website and Github for Windows to manage this project. However, when I try to include the .js or .css files from Github using the Raw links, my browser fails due ...

How to Set Up a Simple Gulp Uglify Configuration

My objective is to compress all .js files within my project and save a minified version in the same directory. Assuming this is the structure of my project directory: project/ gulpfile.js basic.js Project/ Project.js Toolbelt. ...

modifying a record in MongoDB with the help of Mongoose

I need help with updating a collection in MongoDB using Mongoose. function check (db) { var hours = 60 * 60 * 1000 var threeHours = 3 * hours; var lastUpdated = null; db.collection("profile").find({userName: "Rick"}).toArray(function(er ...

I encountered a RangeError with code [ERR_HTTP_INVALID_STATUS_CODE] due to an invalid status code being undefined

I have encountered a specific error while running my note-taking app. The error seems to be related to the following piece of code - app.use((err,req,res,next)=>{ res.status(err.status).json({ error : { message : err.message ...

Tips for aligning the button and search bar in the center:In order

Currently still learning HTML, I'm facing an issue with centering a button and a search bar that are positioned beside each other. Despite trying multiple methods, I haven't been successful in achieving the desired centered layout while keeping t ...

The Owl Carousel npm package is experiencing issues within a ReactJS environment

Currently, I am developing a reactjs application and utilizing the owl carousel npm module to display some data. In my codebase, there is a component dedicated solely to rendering the owl carousel. To achieve this functionality, I have installed the owl c ...

Event that occurs when modifying a user's Firebase Authentication details

Monitoring User Actions with Firebase Authentication Within my application built using Angular, Node.js, and Firebase, I am seeking a method to track user events such as additions, modifications, and deletions. Is there a mechanism to recognize when a us ...

How do I show a personalized cookie banner based on the user's location in a NextJs application?

I have a NextJs 12 application with URLs domain.com and domain.com/es. We implemented the OneTrust cookie banner in _document.ts as shown below: <Head> <Script id="one-trust" strategy="befor ...

Having trouble retrieving a dynamic name with Formcontrol error?

I keep encountering a typeError in this section of code <p *ngIf="formValue.controls['{{obj.name}}'].invalid, but when I manually enter it like this *ngIf="formValue.controls['uname'].invalid it works perfectly fine. What ...