bob
bob

Reputation: 33

jQuery counter and adding a class but not to the first two?

I'm checking list items I have and if there are more than two then I add a class. This works fine but I want the class to start adding after the first two list items. I am not sure how to do that part that excludes adding the class to the first two. Here is my code:

$(document).ready(function() {
  //Checking how many time the class appears
  var numItems = $('ul.singleMagazine li').length;
  if (numItems > 2) {
    alert(numItems);
    //Want to add this class but not to the first two - exclude first two list items and then add it to the rest. How to do it?
    $('ul.singleMagazine li').addClass("newClass");
  }
});

How I would do the excluding part?

Upvotes: 3

Views: 34

Answers (2)

Furquan Khan
Furquan Khan

Reputation: 1594

You can use gt selector. https://api.jquery.com/gt-selector/

$('ul.singleMagazine li:gt(1)').addClass("newClass");

This will add the class only to the li's which are greater than 1. Note here that the indexing starts from 0.

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337656

The li elements should be siblings, so you can use the gt() selector:

$('ul.singleMagazine li:gt(1)').addClass("newClass");

Also note that the length check is redundant as if there's less than two items the above won't do anything anyway.

Upvotes: 2

Related Questions