user3275701
user3275701

Reputation: 97

Count divs with custom attribute by reference

I'm trying to count divs which are created dynamically by javascript by their category attribute and put the result into list with corresponding category attribute value. I think It's not working for because I have problem capturing attribute value in function. Can anyone help me? Thx

<div class='item' category='1'></div>
<div class='item' category='2'></div>
<div class='item' category='1'></div>
<div class='item' category='1'></div>

<ul id='list'>
  <li class='counter' category='1'>Category 1</li>
  <li class='counter' category='2'>Category 2</li>
</ul>

function count_category(){
        if($('#list').length>0){
            $('.counter').each(function(i, obj){
                var count = $('.item[category='+obj.category+']')
                var result = count.length;
                $(this).append('<span>'+result+'</span>');
            });
        }
    }   

    $(document).ajaxComplete(count_category);

Upvotes: 0

Views: 100

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

To get the attribute value use .attr() - obj.category returns undefined

var count = $('.item[category="' + $(this).attr('category') + '"]')

Demo: Fiddle

Upvotes: 1

Related Questions