If your markup is really only a div
, then F. Calder's answer is the way to go.
If you can have other elements and want to ignore them, you should do this:
$("#main > div").filter(function(index) { return index % 4 === 3; }).addClass("last");
Live example | a source
This is because although div:nth-child(4n)
looks like it means every four divs, it is not; this means divs that are 4th, 8th, etc. an element in the parent container. Therefore, if you throw others there, it will not work.
But then again, if you only have div
s, the F answer is the way to go.
source share