The accepted answer wasn't working for me, here is my solution which I've tested in FireFox and Chrome and can say is working. This uses DOMContentLoaded to ensure everything has loaded on the page and can accept a boolean to console.log a unique list or not.
return unique function was sourced from: Get all unique values in a JavaScript array (remove duplicates)
Note: The use of the classList.add / .remove is to remove white space and duplicates from the given tokenlist.
window.addEventListener('DOMContentLoaded', function() {
function getAllStyleClasses(returnUniqueOnly) {
let allTags = document.querySelectorAll('*');
let allClasses = [];
for(let i = 0; i < allTags.length; i++) {
if(allTags[i].classList.length > 0) {
let classes = allTags[i].classList;
allTags[i].classList.add("_");
allTags[i].classList.remove("_");
let nodeArray = Array.from(classes);
allClasses.push(nodeArray);
}
}
let concatClasses = [].concat(...allClasses);
if(returnUniqueOnly == true) {
let uniqueClasses = concatClasses.filter(onlyUnique);
console.log(uniqueClasses);
} else {
console.log(concatClasses);
}
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
}
getAllStyleClasses(true);
}, false);
Edit: I needed to download this list (using the page name as a title) into a text file with line breaks, save file sourced from: How to create a file in memory for user to download, but not through server?
window.addEventListener('DOMContentLoaded', function() {
function getAllStyleClasses(returnUniqueOnly) {
let allTags = document.querySelectorAll('*');
let allClasses = [];
for(let i = 0; i < allTags.length; i++) {
if(allTags[i].classList.length > 0) {
let classes = allTags[i].classList;
allTags[i].classList.add("_");
allTags[i].classList.remove("_");
let nodeArray = Array.from(classes);
allClasses.push(nodeArray);
}
}
let concatClasses = [].concat(...allClasses);
if(returnUniqueOnly == true) {
let uniqueClasses = concatClasses.filter(onlyUnique);
console.log(uniqueClasses);
let txtOutput = uniqueClasses.join().split(",").join("\n")
if(confirm("You're seeing this because you're a developer! Download all styles used on this page?")) {
let pageTitle = document.title.toLowerCase().replaceAll(' ', '-');
save('styles-' + pageTitle + '.txt', txtOutput);
}
} else {
console.log(concatClasses);
}
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
function save(filename, data) {
const blob = new Blob([data], {type: 'text/csv', oneTimeOnly: true });
if(window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
}
else{
const elem = window.document.createElement('a');
elem.href = window.URL.createObjectURL(blob);
elem.download = filename;
document.body.appendChild(elem);
elem.click();
document.body.removeChild(elem);
}
}
}
getAllStyleClasses(true);
}, false);