Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break out of .each() by index number

i want to break out each three items in a list and add a class to that child like;

<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li><!--target list item-->
    <li>4</li>
    <li>5</li>
    <li>6</li><!--target list item-->
    <li>7</li>
</ul>

any idea?

like image 273
Recep Şimşek Avatar asked Apr 14 '12 15:04

Recep Şimşek


2 Answers

You should use the nth-child pseudo selector

$("ul li:nth-child(3n)").addClass("break-here");
like image 63
jorgebg Avatar answered Oct 08 '22 14:10

jorgebg


There's a CSS pseudo selector for that:

:nth-child(xn+y)

selects every x child starting at y, so in your case x = 3 and y = 1 (the default)

$('li:nth-child(3n)').addClass(...);

Demo at http://jsfiddle.net/8WDK4/

See http://www.w3.org/TR/selectors/#nth-child-pseudo and examples

like image 22
Alnitak Avatar answered Oct 08 '22 16:10

Alnitak