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.

3

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

1 Comment

+1. I much prefer this to my answer. Same general idea, but much neater to do it in one line with .filter().
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"); 

Comments

1

do this

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

or

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

1 Comment

The question states pretty clearly that only the li elements with class "Foo" should be affected.
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/

4 Comments

This doesn't answer the question at all. @rkb wanted the first and last list item with the class of foo to be changed.
I said I want to select first and last with class foo. So it's second and forth li in this case.
What if more "foo" elements were added? Then it wouldn't work: jsfiddle.net/2T2yv/15
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.
0

You can use jQuery for this:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.