17

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

John
  • 3,529
  • 14
  • 42
  • 48
  • I'm not sure I get what you're asking; couldn't you just select the list items that have class `selected`? Although I'm not sure you'd want to do that--seems like it'd be better to handle only the single list element that's been expanded. – Dave Newton Sep 20 '11 at 12:25

7 Answers7

38

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.

Xion
  • 22,400
  • 10
  • 55
  • 79
11
$("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.

ipr101
  • 24,096
  • 8
  • 59
  • 61
10

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
}
Dennis
  • 32,200
  • 11
  • 64
  • 79
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.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
2

Or you could try this with size()

if( $("li.success").size() == $("li").size() ){
    //return true
}
Phiter
  • 14,570
  • 14
  • 50
  • 84
0

I am not sure to understand the problem but the check if a jQuery object has a class, you use .hasClass().

Mika Andrianarijaona
  • 1,619
  • 17
  • 29
  • 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. – Boric Jul 03 '19 at 14:57
0

When i understnad you right, you want to set the class selected to all of your li elements when clicking on a ShowAll button?

You don't need to iterate yourself over all lielements.

Just select them and call addClass on them:

$('li').addClass('selected');
Jan
  • 15,802
  • 5
  • 35
  • 59