How to target the first and last elements of sequences with a specific class using CSS

My webpage contains numerous div elements with the class line, each containing a strong.datum element. I want to designate the first and last element of each sequence with the class .active. If this can't be achieved using CSS, is there a way to accomplish it through jQuery?

In the given example, elements with the class .start should include .dt_26, .dt_66, .dt_27, .dt_77, while elements with the class .end should contain .dt_46, .dt_76, .dt_57, .dt_97.

<div class="line">
<strong class="dt_16 app_54 datum">1.6.</strong>
<strong class="dt_26 app_54 datum active">2.6.</strong>
<strong class="dt_36 app_54 datum active">3.6.</strong>
<strong class="dt_46 app_54 datum active">4.6.</strong>
<strong class="dt_56 app_54 datum">5.6.</strong>
<strong class="dt_66 app_54 datum active">6.6.</strong>
<strong class="dt_76 app_54 datum active">7.6.</strong>
<strong class="dt_86 app_54 datum active">8.6.</strong>
<strong class="dt_96 app_54 datum active">9.6.</strong>
<strong class="dt_106 app_54 datum">10.6.</strong>
</div>
<div class="line">
<strong class="dt_17 app_54 datum">1.7.</strong>
<strong class="dt_27 app_54 datum active">2.7.</strong>
<strong class="dt_37 app_54 datum active">3.7.</strong>
<strong class="dt_47 app_54 datum active">4.7.</strong>
<strong class="dt_57 app_54 datum active">5.7.</strong>
<strong class="dt_67 app_54 datum">6.7.</strong>
<strong class="dt_77 app_54 datum">7.7.</strong>
<strong class="dt_87 app_54 datum active">8.7.</strong>
<strong class="dt_97 app_54 datum active">9.7.</strong>
<strong class="dt_107 app_54 datum">10.7.</strong>
</div>

Answer №1

Check out this jQuery solution...

By utilizing the .prev() and .next() functions, you can iterate through all the child elements of the .line element and determine if they are the first or last in their sequence.

I also added a little extra touch just for fun... You can even identify if they're feeling a bit "lonely"... ;)

The code is pretty straightforward to understand:

$(".line").children().each(function(){

    // Check for firsts
    if( $(this).hasClass("active") && !$(this).prev().hasClass("active") ){
      $(this).addClass("first");
    }
  
    // Check for lasts
    if( $(this).hasClass("active") && !$(this).next().hasClass("active") ){
      $(this).addClass("last");
    }
  
    // Check for lonelies
    if( $(this).hasClass("active") && !$(this).prev().hasClass("active") && !$(this).next().hasClass("active") ){
      $(this).removeClass("first last").addClass("alone");
    }
});
.first{
  color: green;
}
.last{
  color: orange;
}
.alone{
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="line">
  <strong class="dt_16 app_54 datum">1.6.</strong>
  <strong class="dt_26 app_54 datum active">2.6.</strong>
  <strong class="dt_36 app_54 datum active">3.6.</strong>
  <strong class="dt_46 app_54 datum active">4.6.</strong>
  <strong class="dt_56 app_54 datum">5.6.</strong>
  <strong class="dt_66 app_54 datum active">6.6.</strong>
  <strong class="dt_76 app_54 datum active">7.6.</strong>
  <strong class="dt_86 app_54 datum active">8.6.</strong>
  <strong class="dt_96 app_54 datum active">9.6.</strong>
  <strong class="dt_106 app_54 datum">10.6.</strong>
</div>
<div class="line">
  <strong class="dt_17 app_54 datum">1.7.</strong>
  <strong class="dt_27 app_54 datum active">2.7.</strong>
  <strong class="dt_37 app_54 datum active">3.7.</strong>
  <strong class="dt_47 app_54 datum active">4.7.</strong>
  <strong class="dt_57 app_54 datum active">5.7.</strong>
  <strong class="dt_67 app_54 datum">6.7.</strong>
  <strong class="dt_77 app_54 datum">7.7.</strong>
  <strong class="dt_87 app_54 datum active">8.7.</strong>
  <strong class="dt_97 app_54 datum">9.7.</strong>
  <strong class="dt_107 app_54 datum">10.7.</strong>

Answer №2

It's my understanding that selecting the first and last element with specific requirements (such as a certain class, etc.) using CSS is not possible. However, achieving this with jQuery is relatively straightforward.

$(document).ready(function() {
  $(".line").each(function(i, line) {
    $(line).children("strong.active:first, strong.active:last").addClass("highlight");
  });
});
.highlight {
  background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="line">
<strong class="dt_16 app_54 datum">1.6.</strong>
<strong class="dt_26 app_54 datum active">2.6.</strong>
<strong class="dt_36 app_54 datum active">3.6.</strong>
<strong class="dt_46 app_54 datum active">4.6.</strong>
<strong class="dt_56 app_54 datum">5.6.</strong>
<strong class="dt_66 app_54 datum active">6.6.</strong>
<strong class="dt_76 app_54 datum active">7.6.</strong>
<strong class="dt_86 app_54 datum active">8.6.</strong>
<strong class="dt_96 app_54 datum active">9.6.</strong>
<strong class="dt_106 app_54 datum">10.6.</strong>
</div>
<div class="line">
<strong class="dt_17 app_54 datum">1.7.</strong>
<strong class="dt_27 app_54 datum active">2.7.</strong>
<strong class="dt_37 app_54 datum active">3.7.</strong>
<strong class="dt_47 app_54 datum active">4.7.</strong>
<strong class="dt_57 app_54 datum active">5.7.</strong>
<strong class="dt_67 app_54 datum">6.7.</strong>
<strong class="dt_77 app_54 datum">7.7.</strong>
<strong class="dt_87 app_54 datum active">8.7.</strong>
<strong class="dt_97 app_54 datum active">9.7.</strong>
<strong class="dt_107 app_54 datum">10.7.</strong>
</div>

The reason why this solution works while something like:

.line > strong.active:first {
  background-color: yellow;
}

does not work is due to differences between the jQuery parsing engine and CSS selectors. In jQuery, :first selects the first element after the specified selectors, whereas in CSS, :first refers to the literal first element regardless of other selectors. Therefore, if CSS selectors remove the literal-first element, :first will not match.

Answer №3

While CSS doesn't have a direct way to achieve this, here is a vanilla JS solution provided with inline explanations:

// Collecting line elements
[...document.querySelectorAll('.line')].forEach(function(line) {
  // Iterating through child elements
  [...line.querySelectorAll('strong')].reduce(function(p,c) {
    if (c.classList.contains('active')) {
      if(!p) // Add 'first' for the first active element
        c.classList.add('first');
       // Add 'last' for the last active element in each group
      if((!c.nextElementSibling || !c.nextElementSibling.classList.contains('active')) && p)
        c.classList.add('last');
      return true;
    }
    return false;
  }, false);
})
.first {
  color: cadetblue;
}

.last {
  color: red;
}
<div class="line">
  <strong class="dt_16 app_54 datum">1.6.</strong>
  <strong class="dt_26 app_54 datum active">2.6.</strong>
  <strong class="dt_36 app_54 datum active">3.6.</strong>
  <strong class="dt_46 app_54 datum active">4.6.</strong>
  <strong class="dt_56 app_54 datum">5.6.</strong>
  <strong class="dt_66 app_54 datum active">6.6.</strong>
  <strong class="dt_76 app_54 datum active">7.6.</strong>
  <strong class="dt_86 app_54 datum active">8.6.</strong>
  <strong class="dt_96 app_54 datum active">9.6.</strong>
  <strong class="dt_106 app_54 datum">10.6.</strong>
</div>
<div class="line">
  <strong class="dt_17 app_54 datum">1.7.</strong>
  <strong class="dt_27 app_54 datum active">2.7.</strong>
       <!-- More HTML code goes here -->
</div>

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

Using CSS3 gradient in grey instead of white

I came across an amazing example by Chris Coyier showcasing a "read more" button. I attempted to replicate this by creating a simple fadeout effect from white to transparent, but unfortunately, I ended up with a grey gradient instead. You can view my atte ...

Implement a validation check within a text box by utilizing JQuery

I am attempting to insert a validation symbol (a green check mark) inside a text box once a user fulfills specific criteria. My approach involves using JQuery for implementation. I have made an attempt using Fontawesome icons with the following code, but i ...

Customize CSS for Vimeo's HTML5 player

Can I customize Vimeo's HTML and CSS attributes? I have a video that autoplays and I don't want the play button. I want to modify this specific class. .a.l .b .as { position: absolute; top: 50%; left: 50%; margin: -2em 0 0 -3.25em; float: none; ...

Guide on Highcharts Bar Chart: Adjusting the Minimum Bar Width/Length

We are currently experiencing some challenges within our application where bars are not displaying if a particular value is significantly smaller compared to the largest value. To better illustrate this issue, you can refer to the following jsFiddle: http ...

Is the PNG image displaying poorly in the IE10 browser?

My application features a PNG image with actual dimensions of 300px X 300px. I am using a 20% scale of this image as an input image button, which displays correctly in Mozilla and Chrome browsers. However, in IE, the image appears distorted. Please refer t ...

What is the best way to adjust the height of a row in a Material UI table using CSS

I've been attempting to establish a row height of 30px for a table (https://material-ui.com/components/tables/), but it seems that the minimum I can set is 53. Why is this restriction in place? How can I adjust the row height to 30px using CSS based ...

Navigation bar with dropdown functionality that adjusts its width based on the content inside

Need help with a CSS dropdown menu issue on my WordPress site. The contents of the submenus are too wide, even after setting a static width for them. I'm looking for a way to make the submenu width adjust dynamically based on the title length. Any exp ...

Toggle the visibility of DIV content based on the current URL

In my HTML page, I have a div-reportControlPanel as shown below. Additionally, I have included another div-reportControlPanel1 with a different ID. <div id="reportControlPanel" class="pentaho-rounded-panel-bottom-lr pentaho-shadow"> <div id="prom ...

html form-- assistance required in making new input area appear upon clicking radio button

Currently, I am in the process of creating a basic customer database using mysql and php. My goal is to have extra input fields appear for mailing address when users click on the radio button labeled "different mailing address". However, I'm unsure ab ...

Error message: Fancybox unable to open PDF file - ReferenceError: href is not defined

I came across some really interesting code on a website detailing how to open a PDF within a Fancybox iframe. However, I am trying to implement this into a CSS Menu that I generated using PHP. When I try to run the code, I receive an error message in the G ...

Create a copy of a JQuery slider

Hello there, I'm a first time poster but have been reading for a while now. I've been working on creating a simple jQuery Slider and I'm facing an issue... I want to create a slider that utilizes minimal jQuery and can be easily duplicated o ...

Position the background in CSS according to the class name

There are a total of 8 icons, with 4 in blue and 4 in grey. Therefore, product 1 has both a blue icon and a grey icon. When the user has product 1, they will see the blue icon (with an added class on the container called .gotProduct), and when they don&ap ...

It appears that the .fadeOut() function is not working properly when applied to an image

I want my input text box to automatically submit the form and display a checkmark image after the user has been idle from typing. I tried implementing a fadeout function for the image but it doesn't seem to be working. var timer = null; $('.form ...

HTML/CSS - How to make an element wider than its containing element while staying visible

I am currently working on a web page that generates a table with a green background labeled by an h2 element. The challenge I'm facing is ensuring that the h2 element extends horizontally as far as the user scrolls so that there is always a green bar ...

Having trouble integrating SVG icons into my Angular project

I'm encountering an issue with adding icons that I've designed in Figma to my web application. Some of the icons are displaying correctly while others are not. Here is the code snippet I am using to add the icons: .dx-icon-info { mask-image: ...

Exploring the world of jQuery and Ajax: Experimenting with implementing a POST method through Ajax and retrieving the response in HTML

Hey guys, I'm currently attempting to set up a basic HTML post method using Ajax. Take a look at the code snippet below: <?PHP function fetchInstagramData($url) { $ch = curl_init(); curl_setopt_array($ch, array( CURLOPT_URL => ...

What could be causing the unexpected white gap within my div element even though I've adjusted its dimensions to be minimal?

<div style=" height:0; width: 0 ; border: 1px solid black ; "> This code snippet displays a div element with a specified height, width, and border color. However, there seems to be an issue with the rendering as some st ...

The Save button is unresponsive when using jQuery-UI Connected Sortable Lists

When attempting to Test Drag&Drop element with connectedSortable from sortable1 on the left side and sortable2 on the right side, I encountered an issue where the array data results are not being sent to save in my database upon clicking the Save Butto ...

Position the Material UI Box element to the bottom of its parent container

Hello there, I've come across the following layout: <Box width="100%" height="100%" p={1}> <Box my={1} display="flex" justifyContent="center"> </ ...

Establish the height of the root to be the same as the height

As a newcomer to HTML and CSS, I am struggling with setting the background color of my root div on a webpage. My code is quite complex, but let me simplify the issue for you by providing a sample problem below. <style> #background{ background-c ...