Check if all items have the same class

26,008

Solution 1

You can probably count the list items with selected class against all list items:

if ($("#questions li.selected").length == $("#questions li").length) {
    // all list items are selected
}

#questions is the element that contains your list and of course it might be different in your code, but you should get the idea.

Solution 2

$("li:not(.selected)").length

Would give you the number of <li>s that do not have the 'selected' class. If this figure was zero you could run your logic.

Solution 3

Select all list items, filter out the items belonging to a certain class and then determine whether or not there are any left over:

if($("li").not(".className").length > 0 ) {
    //code
}

Solution 4

You could compare the number of li elements to the number of li elements with the class "selected". If those numbers are the same, then all the li elements have that class:

if($("li").length == $("li.selected").length) {
   //All li elements have class selected
}

You can do this at any point, it does not have to go inside an each loop.

Solution 5

Or you could try this with size()

if( $("li.success").size() == $("li").size() ){
    //return true
}
Share:
26,008
John
Author by

John

Updated on March 04, 2020

Comments

  • John
    John over 4 years

    I built a FAQ page with the option to hide and show the content underneath each question. I have a "Expand all" functionality that let the user display all the questions onclick. When a question is expanded it gets a class of "selected".

    I am trying to change the "Expand All" status when all questions (LIs) are expanded.

    How can I check that all the LI have the CLASS "selected" at the same time?

    I use the EACH method to get the LIs and their CLASS.

    Thanks in advance

  • Boric
    Boric about 5 years
    This does not determine if every element in the list has the specified class, but only whether any of the elements do. If only one element does, or if all elements do, it will return true either way.