wyc
wyc

Reputation: 55273

Using jQuery to apply a style to only even elements (2, 4, 6, etc.) within a div?

I want ot apply a style to some elements within a div:

<div id="showcase">
 <div class="project">
 <div class="project"> <!-- add a style here -->
 <div class="project">
 <div class="project"> <!-- add a style here -->
 <div class="project">
 <div class="project"> <!-- add a style here -->
</div>

The project divs are Wordpress posts so I can't just add the class in the div. So I think jQuery is the way to go.

Any suggestions?

Upvotes: 1

Views: 89

Answers (2)

silex
silex

Reputation: 4320

http://jsfiddle.net/uAZgm/

$('#showcase .project:nth-child(even)').addClass('new');

Upvotes: 0

Emil Ivanov
Emil Ivanov

Reputation: 37633

$('.project:odd').addClass('myclass');

http://api.jquery.com/odd-selector/

For optimal performance you should do:

$('.project').filter(':odd').addClass('myclass');

As James pointed out (and the docs above) :odd is used instead of :even because counting is 0 based.

Upvotes: 9

Related Questions