Search code examples
jqueryhtmljquery-filter

Put a class on every list item in the third row with jQuery filtering


I have a media gallery. For some weird reason, the designer decided to put these media items in blocks of 12. Three rows, four items per row and then a gap.

Now I do not feel like putting a list of 12 items in a parent list per block. I thought this could easily be handled by jQuery filtering, adding a class on every item of every third row.

I know how to target every :nth(4) item, every fourth item in the list, but how do I do every item in the third row?

What filter can I use for something like that?

The markup is listed below. All items are just floating elements in a unordered list.

<ul>
    <li><img src="#"></li>
    <li><img src="#"></li>
    <li><img src="#"></li>
    <li><img src="#"></li>
    <li><img src="#"></li>
    <li><img src="#"></li>
    <li><img src="#"></li>
    <li><img src="#"></li>
    <li><img src="#"></li>
    <li><img src="#"></li>
    <li><img src="#"></li>
    <li><img src="#"></li>
    <li><img src="#"></li>
    <li><img src="#"></li>
    <li><img src="#"></li>
    <li><img src="#"></li>
    <li><img src="#"></li>
    <li><img src="#"></li>
    <li><img src="#"></li>
</ul>

Floating, and four items fit per row. So I would need to target item 9, 10, 11 and 12, but also three rows further, item 21, 22, 23, 24 and again...

I thought I could do it with some nifty calculation in the .filter(function(){});, but I'm not even close to the correct answer yet...

What I want to have is actually visible in this jsfiddle I just made: http://jsfiddle.net/DpMRc/5/**

I want to target the blue boxes with a .filter() function instead of having to write the whole for loop for it.


Solution

  • I presume you're using jQuery because you want IE8 support, but in all other browsers (including IE9), you can do this with just CSS:

    li:nth-child(12n+9), li:nth-child(12n+10), li:nth-child(12n+11), li:nth-child(12n+12) {
        border-bottom: 4px solid red;
    }
    

    Here's a working example, I've made a guess as to what a simplified version of the rest of your CSS would look like. The same selectors will work in jQuery if you want to polyfill for IE, but I would suggest you do that in conditional comments so as to not waste time on other browsers.