6

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

pumpkinzzz
  • 2,907
  • 2
  • 18
  • 32

4 Answers4

6

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

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

pumpkinzzz
  • 2,907
  • 2
  • 18
  • 32
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
0

what about

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

You can use JavaScript or jQuery

$('custom').prev().css('color', 'red');
m4n0
  • 29,823
  • 27
  • 76
  • 89
bnnoor
  • 656
  • 2
  • 13
  • 31
-2

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/

gvperkins
  • 168
  • 2
  • 9