3

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?

1
  • you can use gt() selector. Commented Jun 5, 2018 at 12:25

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Hi Rory, thank you for this. Is gt() new in jquery? I've never come across it in years.... Thank you!
Glad to help, and not really - it was added in 1.0: api.jquery.com/gt-selector
Thanks again, shame I've not come across it beforehand!
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.