Asked  7 Months ago    Answers:  5   Viewed   37 times
<ul>
    <li class="list">test1</li>
    <li class="list">test2</li>
    <li class="list">test3</li>
    <li>test4</li>
</ul>

How do I select the "last child" with the class name: list?

<style>
    ul li.list:last-child{background-color:#000;}
</style>

I know the example above doesn't work, but is there anything similar to this that does work?

IMPORTANT:

a) I can't use ul li:nth-child(3), because it could happen that it's on the fourth or fifth place too.

b) No JavaScript.

 Answers

23

I suggest that you take advantage of the fact that you can assign multiple classes to an element like so:

<ul>
    <li class="list">test1</li>
    <li class="list">test2</li>
    <li class="list last">test3</li>
    <li>test4</li>
</ul>

The last element has the list class like its siblings but also has the last class which you can use to set any CSS property you want, like so:

ul li.list {
    color: #FF0000;
}

ul li.list.last {
    background-color: #000;
}
Tuesday, June 1, 2021
 
laurent
answered 7 Months ago
84

No, it's not possible using just one selector. The :first-of-type pseudo-class selects the first element of its type (div, p, etc). Using a class selector (or a type selector) with that pseudo-class means to select an element if it has the given class (or is of the given type) and is the first of its type among its siblings.

Unfortunately, CSS doesn't provide a :first-of-class selector that only chooses the first occurrence of a class. As a workaround, you can use something like this:

.myclass1 { color: red; }
.myclass1 ~ .myclass1 { color: /* default, or inherited from parent div */; }

Explanations and illustrations for the workaround are given here and here.

Tuesday, June 1, 2021
 
oroshnivskyy
answered 7 Months ago
11

Unfortunately, there is no way (at least none I know of) to select nth-of-type of a class, since nth-of-class doesnt exist. You will probably have to add a new class to every third .module manually.

Tuesday, June 1, 2021
 
nhunston
answered 7 Months ago
76

Shoulb be something like

tr:nth-child(4n+1) {
  declarations
}
Wednesday, September 1, 2021
 
Shai Rado
answered 4 Months ago
34

You can use the last method:

var last = $(this).find("ul.someClass").last();

Or the :last selector:

var last = $(this).find("ul.someClass:last");
Saturday, December 4, 2021
 
tompave
answered 5 Days ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share