2

I have the following list

    <ul class="list">
        <li>1</li>
        <li class="foo">2</li>
        <li class="foo">3</li>
        <li class="foo">4</li>
        <li>5</li>
    </ul>

I want to change the color of first and last li's, which has class foo, using css

.list .foo:first-child,
.list .foo:last-child {
  color: red;
}

But it select nothing. Check this fiddle.

How can I select first and last li's with class foo. If it's not possible with css then how can I do it with jQuery.

user229044
  • 232,980
  • 40
  • 330
  • 338
rkb
  • 514
  • 2
  • 9
  • 19

5 Answers5

6

I don't think there is a css selector solution for this, you can use jQuery to assign a class

.selected {
    color: red;
}

then

$('.list li.foo').filter(':first, :last').addClass('selected')

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • +1. I much prefer this to my answer. Same general idea, but much neater to do it in one line with `.filter()`. – nnnnnn Jan 25 '14 at 06:06
1

do this

$('.list li.foo').filter(':first, :last').css( "color", "red" );

or

$('.list li.foo:first,.list li.foo:last').css( "color", "red" );
Nomi Ali
  • 2,165
  • 3
  • 27
  • 48
  • The question states pretty clearly that only the li elements with class "Foo" should be affected. – nnnnnn Jan 25 '14 at 05:53
1

I don't think this can be done with just CSS, but it is simple with jQuery. Here's one way:

var $lis = $("ul.list li.foo");
$lis.first().addClass("someClass");
$lis.last().addClass("someClass");

With:

.someClass {
    color: red;
}

Demo: http://jsfiddle.net/2T2yv/10/

Or a slightly different solution that doesn't repeat .addClass():

var $lis = $("ul.list li.foo");
$lis.first().add($lis.last()).addClass("someClass");
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
0
.list .foo:nth-child(2n)
{
    color: green;
}

and Html is

 <ul class="list">
    <li>1</li>
    <li class="foo">2</li>
    <li class="foo">3</li>
    <li class="foo">4</li>
    <li>5</li>
</ul>

Fiddle

For better understanding nth-child (pseudo-selector) you can go through this http://css-tricks.com/how-nth-child-works/

Karuppiah RK
  • 3,894
  • 9
  • 40
  • 80
  • 3
    This doesn't answer the question at all. @rkb wanted the first and last list item with the class of foo to be changed. – Josh Davis Jan 25 '14 at 05:50
  • 1
    I said I want to select first and last with class `foo`. So it's second and forth `li` in this case. – rkb Jan 25 '14 at 05:51
  • 1
    What if more "foo" elements were added? Then it wouldn't work: http://jsfiddle.net/2T2yv/15/ – nnnnnn Jan 25 '14 at 06:03
  • This works in this case but what if I add one more `li` element to the end without class `foo`, your css will also make that red. – rkb Jan 25 '14 at 06:04
0

You can use jQuery for this:

$('.list li.foo').first().css('color', 'red');
$('.list li.foo').last().css('color', 'red');
Kunj
  • 1,980
  • 2
  • 22
  • 34