Count Divs with jQuery

I’ve been working with a few plugins lately that have templates, but do not allow for editing for the loop, so I’ve been unable to add counters with PHP.

I’ve found a way around this using .each() and jQuery conditional logic.

In the below example, each Blog post div is counted, and a custom class is added in a repeating pattern of 1-4.

jQuery('.blog-post').each( function (index) {
index += 1;
if (index % 4 == 1) {
jQuery(this).addClass("article-one");
} else if (index % 4 == 2) {
jQuery(this).addClass("article-two");
} else if (index % 4 == 3) {
jQuery(this).addClass("article-three");
} else if (index % 4 == 0) {
jQuery(this).addClass("article-four");
}
});

Source.

Leave a Reply

katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.