Reputation: 35734
It doesnt seem to be possible to get every second element with a specific class name in either jquery or css.
Specfically im trying the nth-child selector in both like so:
$( ".mylist li.myitem:nth-child(2n)")
If i have a list like this:
<ul>
<li class="myitem">Item 1</li>
<li class="myitem">Item 2</li>
<li>Item 3</li>
<li class="myitem">Item 4</li>
<li class="myitem">Item 5</li>
</ul>
I would like to target item 2 and item 5.
(this list above is a sample, it is the underlying technique i need to get i.e. to get every second element with a specific class) Is this possible?
Upvotes: 2
Views: 1406
Reputation: 99
The jQuery selector :odd
will return every second element in the order of its appearance in the document. In your case...
$('.myitem:odd')
will return
[<li class="myitem">Item 2</li>, <li class="myitem">Item 5</li>]
Upvotes: 0
Reputation: 318212
For elements that are not siblings, you could use the index
var items = $('.myitem');
items.filter(function() {
return items.index(this) % 2;
}).css('color','red');
Upvotes: 1
Reputation: 44740
You can use :odd
selector
$("ul li.myitem:odd").addClass('red');
Demo -->
http://jsfiddle.net/Uhv27/
Upvotes: 1
Reputation: 38252
In your case you can do this with CSS:
.myitem + .myitem {
/*Styles Here*/
}
With this you target an element with class myitem
that is right after another with class myitem
.
Check this Demo Fiddle
Upvotes: 1