0

I am trying to count li elements with data-filter-class "men". Below is the code snippet.

<ul id="cards">
    <li data-filter-class="men"></li>
    <li data-filter-class="women"></li>
    <li data-filter-class="men"></li>
    <li data-filter-class="kids"></li>
    <li data-filter-class="women"></li>
    <li data-filter-class="men"></li>
</ul>
var filterType ='men'; //filter type received at runtime.
var category_count = $('#cards li[data-filter-class="+filterType+"]').length;
console.log(filterType + " count " + category_count);

Results : 0 Expected: 3

Actually

var category_count = $('#cards > li').length;

Results : 6

Can someone please point out where I am getting wrong in the first query? I am new to learning jQuery so please excuse me.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
vinitb4u
  • 43
  • 1
  • 5

2 Answers2

0

Your category_count does not have proper string interpolation, you will want to filter like so:

var category_count = $('#cards li[data-filter-class="'+filterType+'"]').length;
Tomanow
  • 7,247
  • 3
  • 24
  • 52
0

You forget to close string while using filterType, see correct code

$('#cards li[data-filter-class="'+filterType+'"]').length;
Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57