[英]How to find most frequent used class on a web page with Javascript or jQuery?
Wondering if there's a way to show the list of classes used on a page with # of times it occurs on the page. 想知道是否有一种方法可以显示页面上使用的类的列表,并显示该页面上出现的次数。 Like so:
像这样:
sublevel | 12
tag | 10
main | 1
Use the CSS Attribute Selector to select all the elements that have the attribute class
. 使用CSS属性选择器选择具有属性
class
所有元素。 Then loop through each element of the set, accessing its className
property and counting the occurences of each class: 然后遍历集合的每个元素,访问其
className
属性并计算每个类的出现次数:
var classes = {}; // the classes counter document.querySelectorAll("[class]").forEach(function(el) { // select all the element that have a class attribute el.className.trim().split(/\\s+/).forEach(function(clazz) { // get the className of this element, trim it, and split it into individual classes // for each class, increment or initialize the counter if(classes[clazz]) classes[clazz]++; else classes[clazz] = 1; }); }); console.log(classes);
<div class="AB"> <span class="B"></span> </div> <p class="ABC"></p>
There is no built-in API for something like this. 没有类似这样的内置API。 You need to inspect the class names of every element.
您需要检查每个元素的类名称。 To get every element you either have to walk the DOM or get a list of all elements and iterate over them.
要获取每个元素,您必须遍历DOM或获取所有元素的列表并对其进行迭代。 Here is a simple solution that does the latter:
这是执行后者的简单解决方案:
const classes = new Map();
for (let elem of document.querySelectorAll('*')) {
for (let cls of elem.classList) {
classes.set(cls, (classes.get(cls) || 0) + 1);
}
}
const rankedClasses = Array.from(classes).sort((a,b) => b[1] - a[1]);
Can't say whether walking the DOM is more efficient or not. 无法说走DOM是否更有效率。
Same as most of the others: get all elements and loop over them, counting the number of times each className appears. 与大多数其他方法相同:获取所有元素并遍历它们,计算每个className出现的次数。 Only difference is it tries to be compatible with browsers back to say ES5.
唯一的不同是它尝试与回到ES5的浏览器兼容。 Needs reduce , forEach and Object.create polyfills for IE 8.
需要reduce , forEach和Object.create IE 8的polyfills。
function countClasses(root) { root = root || document; return [].reduce.call(root.getElementsByTagName('*'), function (classes, el) { (el.className.match(/\\S+/g) || []).forEach(function(cls) { classes[cls]? ++classes[cls] : classes[cls] = 1; }); return classes }, Object.create(null)); } console.log(countClasses());
<div class="foo bar"> <span class="foo"></span><span class="bar fum"></span><span></span> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.