pumpkinzzz
pumpkinzzz

Reputation: 2967

CSS selector for :last-child in a subset selection

assuming i have a structure like this (and can't modify it):

<ul>
    <li class="common">   <p>First A</p>   </li>
    <li class="common">   <p>Second A</p>   </li>
    <li class="common">   <p>Third A</p> </li>
    <li class="common">   <p><b>SELECT ME</b></p>   </li>
    <li>   <p>First B</p>   </li>
    <li>   <p>Second B</p>   </li>
    <li>   <p>...</p>   </li>
</ul>

Is there a way to select the last element with class "common"? (in this case the fourth element)

First i tried selecting a subset with:

.common{
    background: red;
}

and it worked correctly. So i tried selecting last-child of them, with:

.common:last-child{
    background: green;
}

but not luck. i also would like to avoid adding a class for that element.

Jsfiddle

EDIT: i simplified classes and selectors to make it cleaner

Upvotes: 6

Views: 444

Answers (4)

what about

.common:last-of-type {
  background: green;
}

Upvotes: 0

BoltClock
BoltClock

Reputation: 723538

Is there a way to select the last element with class "common"?

No, not with a CSS selector without modifying the HTML.

Upvotes: 6

gvperkins
gvperkins

Reputation: 178

If your not against a JS route you could do this

$('li.common.custom').first().prev('.common').css('background','yellow');

It finds the first element that has both .common and .custom classes and then goes to the previous element. So its technically the last element that only has .common

https://jsfiddle.net/89z20341/

Is the structure going to stay exactly as you have coded it? eg with the bold tags on the element you want to select?

if so could you just do this

.common p b{
background: green;
display:block;

}

http://jsfiddle.net/seLm589s/4/

Upvotes: -2

bnnoor
bnnoor

Reputation: 696

You can use JavaScript or jQuery

$('custom').prev().css('color', 'red');

Upvotes: -2

Related Questions