Group and count HTML elements by data attribute in jQuery

前端 未结 5 480
小鲜肉
小鲜肉 2020-12-19 05:58

I\'m trying to group each instance of a data attribute into a list from the number of occurrences of each attribute in a page, using jQuery. Similar to grouping categories o

5条回答
  •  轮回少年
    2020-12-19 06:20

    If data attribute is on span or div inside then you have to use find. Find is more costly in term of DOM search. Is better to just add class on that elements where you have data-attribute and loop through and get information.

    /*
     * fetch labels from list by data attribute
     * 
     */
    
    function fetch_labels() {
    
        var leadssource = {},
                lead;
    
        $('#leads-list tr').each(function(i, el) {
    
            lead = $(el).find('[data-leadsource]').data('leadsource');
            if (leadssource.hasOwnProperty(lead)) {
                leadssource[lead] += 1;
            }
            else {
                leadssource[lead] = 1;
            }
        });
    
        return leadssource;
    }
    

提交回复
热议问题