'How to get list of Css class use in the HTML file?
I need list of classes used in an html file. Is there any tool where i can get list of classes in the HTML file?
Solution 1:[1]
This should work and it doesn't need jquery:
const used = new Set();
const elements = document.getElementsByTagName('*');
for (let { className = '' } of elements) {
for (let name of className.split(' ')) {
if (name) {
used.add(name);
}
}
}
console.log(used.values());
Solution 2:[2]
If you've got jQuery on the page, run this code:
var classArray = [];
$('*').each(function(){if(this.className!=""){classArray.push(this.className)}})
The variable classArray will contain all the classes specified on that HTML page.
Solution 3:[3]
Pure Javascript Code will list all the unique classes.
var lst=[];
document.querySelectorAll("[class]").forEach( (e)=>{
e.getAttribute("class").split(" ").forEach( (cls)=>{if( cls.length>0 && lst.indexOf(cls)<0) lst.push(cls);}
);
});
console.log(lst.sort());
Solution 4:[4]
Take a look at Dust Me Selectors.
It's not exactly what you are looking for, it shows a list of UNused selectors. However, I imagine you could use the inverse of the list it provides.
Here is the link: http://www.sitepoint.com/dustmeselectors/
Solution 5:[5]
I know this is an old question, but got here through google so I suspect more people can get here too.
The shortest way, using querySelectorAll and classList (which means, browser support could be an issue: IE10 for classList and IE8 for querySelectorAll ), and with duplicates, would be:
var classes = 0,
elements = document.querySelectorAll('*');
for (var i = 0; i < elements.length; i++) {
classes = classes + elements[i].classList.length;
}
I made a jsFiddle with a fallback for classList (which has the "lowest" browser support) that also counts all elements, all classes and all elements with classes if you're not using classList
.
I didn't add a unique detection though, might get to it some day.
Solution 6:[6]
Quickly list classes from console (ignoring 'ng-*' angular classes)
(global => {
// get all elements
const elements = document.getElementsByTagName('*');
// add only unique classes
const unique = (list, x) => {
x != '' && list.indexOf(x) === -1 && x.indexOf('ng-') !== 0 && list.push(x);
return list;
};
// trim
const trim = (x) => x.trim();
// add to variable
global.allClasses = [].reduce.call(elements, (acc, e) => e.className.split(' ').map(trim).reduce(unique, acc), []).sort();
console.log(window.allClasses);
})(window);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | MisterGreen |
Solution 3 | garish |
Solution 4 | nikmd23 |
Solution 5 | LasagnaAndroid |
Solution 6 | Ferenc Takacs |