Tips for selecting the initial and final elements of a specific class

Here is a simple example of table markup:

<div class="table">
  <div class="table__headers"></div>
  <div class="table__row"></div>
  <div class="table__row"></div>
</div>

The CSS styling for this table looks like this:

<style lang="scss" scoped>
.grid {
    display: grid;
    grid-gap: 0.5rem;
}

.table {
    &__headers,
    &__row {
        @extend .grid;
        padding: 0.5rem 0.75rem;

        :first-child {
            text-align: start;
        }

        :last-child {
            text-align: end;
        }

        p {
            font-size: 0.8rem;
            font-weight: bold;
            text-align: center;
            margin: 0;
        }
    }

    &__row {
        background: #f8f8fa;
    }
}
</style>

The challenge faced is with targeting the first and last table__row elements for unique styling.

Unfortunately, using :first-of-type does not work as expected, while :last-of-type does. Any assistance on this issue would be greatly appreciated!

Thank you,

Answer №1

Check out this JavaScript solution:

let allRows = document.querySelectorAll(".table__row"); // Selecting all rows and storing them in an array-like object
allRows[0].classList.add("firstRowStyle");                   // Adding style to the first row
allRows[allRows.length-1].classList.add("lastRowStyle");        // Styling the last row
.firstRowStyle { background-color:blue; }
.lastRowStyle { background-color:yellow; }
<div class="table">
  <div class="table__headers"></div>
  <div class="table__row">content</div>
  <div class="table__row">content</div>
  <div class="table__row">content</div>
  <div class="table__row">content</div>
  <div class="table__row">content</div>
  <div class="table__row">content</div>
</div>

Answer №2

The main issue causing :first-of-type to fail is that it acts as :nth-child(1), but for this specific case, you should use :nth-child(2) because of the preceding <div> element.

Keep in mind that these selectors are designed to target elements by their tag names, not classes.

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

OpenLayers' circular frames surrounding the icons

I am currently using openlayers and trying to implement a feature that creates a circle around the icons on the map. I have been referring to this example on Stack Overflow but unable to draw the circle successfully. Can someone please assist me with this? ...

The context provider in Next.js wraps the App component with a layout component specific to each page, resulting in data

Within my project, I have an authentication context component wrapping the main app component. Simultaneously, I am also attempting to implement a page-specific layout component based on the Next.js documentation found here. I'm unsure if my approach ...

The bootstrap switch button remains in a neutral grey color

Ordinary: Initially clicked: Click again: After the second click, it remains grey and only reverts on a different action like mouse click or selection. Is there a way to make it go back to its original state when unselected? ...

JSReports encountered an unexpected token "<" in the JSON at position 0

Seeking assistance from those knowledgeable in JSReports, but open to suggestions from all... I've investigated the common issue of "unexpected token < in JSON at position 0", which typically arises when attempting to parse an HTML-formatted strin ...

Retrieve information using PHP with AJAX without revealing it on the screen

Is it feasible to fetch data using Ajax in PHP and store them in a JS variable without displaying it? I require this data for date manipulation but do not want to show it. When I attempted to merely return the data without echoing it, the Ajax data in JS ...

Tracking triggered JavaScript events (across all browsers)

Although this query may have been addressed previously, the responses mostly pertain to browser-specific techniques. My inquiry is straightforward: Is there a method to observe all triggered events (specifically the fired event and the corresponding elemen ...

Execute a Google Analytics Request within a Chrome Extension Background Script

Here's a code snippet that I'm working on. It's supposed to send a daily "order" to Google Analytics to track the number of daily uses installed. I've set the interval for testing purposes to 5 seconds, but it doesn't seem to be wo ...

Looking for assistance on how to automatically close the sidebar or pull navigation menu after clicking on a menu item

My website is designed to be responsive and includes a navigation slider that is hidden off-screen by default. The slider features a vertical push/pull bar that remains visible for users to access the menu. The entire navigation slider is fixed on the page ...

Vuejs - Trouble with Component Rendering on the Screen

I'm currently working on developing a Vue application for monitoring and managing budgets. I have a BudgetItems component that I intend to display in the /budget route. Although all other components and raw HTML are successfully rendering, this specif ...

Implementing a Div response within the actionPerformed method

I've spent hours working on this javascript/ajax code trying to get it to add a div response that was echoed by a php script. Any assistance with this would be greatly appreciated. <form id="form1" name="form1" method="post" enctype="multipart/for ...

Error message: "Vue-i18n is not defined in the vuex

I've been attempting to update the locale in my Vue project using Vuex and VueI18n. Initially, I thought I had figured out a way to update the locale by setting the i18n value in the store object and then using it like this (mutation): UPDATE_LAN ...

Encountered an issue during the installation of react router - in need of assistance to resolve the error

Encountering an Error Error Message when Installing React Router DOM: npm WARN: The use of global `--global` and `--local` is deprecated. Use `--location=global` instead. npm ERR! code EPERM npm ERR! syscall mkdir npm ERR! path D:\ npm ERR! errno -404 ...

Retrieving JSON data from a PHP file through a standalone JavaScript script

I am in need of creating a JavaScript file that will assign values to two variables within a PHP file. The PHP file should then construct a JSON structure and display some data. My goal is to have a form written in JavaScript with two input fields that wi ...

IE11 experiences frequent crashes when running a web application utilizing the Kendo framework and JavaScript

I am experiencing difficulties with my ASP.NET MVC application that utilizes Kendo UI and jQuery. Specifically, when using Internet Explorer 11, the browser crashes after a short period of usage. The crash does not seem to be linked to any specific areas o ...

Django - tallying timer in action

Looking to add a timer that begins when accessing this template: {% block content %} <h3>C-Test</h3> <p>In the text below, some word endings are missing. The gap is about half the length of the word, so you need to fill in the rest ...

Prevent automatic refreshing of React app on remote devices

My friend and I are collaborating on the development and testing of a React app simultaneously. He accesses the app from my machine using my IP address but encounters an issue where every time I save something in the code, the app reloads on both of our ...

The swap feature in drag-and-drop does not have a defined function

I am currently developing a to-do app that utilizes drag and drop functionality to reorder items in the list. However, I have encountered an issue where swapping elements works perfectly for the first five elements but throws errors when dealing with the s ...

Upon sending a POST request to http://localhost:5000/getData, a 404 error (Not Found) was encountered while using axios

As a newcomer to react and node.js, I have set up a fake server running on port 5000 with an API (http://localhost:5000/getData) that contains a hardcoded array of objects. My goal is to add a new object to this API from my react frontend running on port 3 ...

Discovering uncategorized elements using javascript

Let's say I have a piece of HTML with some content that is not wrapped in any tags, like this: <html> <body> <p>text in a tag</p> other text outside any tag </body> </html> Is there a way to access the untagged el ...

Tips for retrieving the ID of a newly added Firestore document in Vue.js

I am currently using Vue.js and Firebase to create a very basic CRUD functionality. One issue I have encountered is that when I create data from a form and send it to the database, there is no document id available for updating my local array of objects. ...