简体   繁体   中英

Count html5 data attributes

I'm trying to count how many elements (list) have the html data attribute of 'data-facet', but I'm undefined.

Here is what I have tried:

$('li').data('facet').length;

Any ideas where I've gone wrong?

If data('facet') represents an integer, then that would explain the undefined result (because you can't run .length on an integer). You can fix this by doing $('li').data('facet').toString().length; instead, but that's not going to get you the result you want (instead, it will give you the length of the data-facet value of the first li element).

To get the desired count of li s, do this:

$('li[data-facet]').length

That will give you the number of li element that have the data-facet attribute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM