Samuel Elh Samuel Elh - 2 months ago 5
Javascript Question

How to detect if at least one list item has a class name

How to detect if at least one of the

li.tst
list items has a
.count
class and then display
.msg
division ?

<ul>
<li class="tst 1 na">li</li>
<li class="tst 2 na">li</li>
<li class="tst 3 count">li count</li>
<li class="tst 4 na">li</li>
</ul>
<div class="msg" style="display: none;">has count</div>


Examples:

Has count: true:

<ul>
<li class="tst 1 count">li</li>
<li class="tst 2 na">li</li>
<li class="tst 3 count">li count</li>
<li class="tst 4 na">li</li>
</ul>
<div class="msg" style="display: block;">has count</div>


Has count: false:

<ul>
<li class="tst 1 na">li</li>
<li class="tst 2 na">li</li>
<li class="tst 3 na">li count</li>
<li class="tst 4 na">li</li>
</ul>
<div class="msg" style="display: none;">has count</div>


Anyway to do that with Jquery ? I hope this I am not duplicating.

Answer

You can get all li that has class count, like so

var $msg = $('.msg');

if ($('ul > li.count').length) {
    $msg.show();    
} else {
    $msg.hide();  
}

and then check .length

Example