As you do when your CSS files start to mount up and get messy (or at least in our case) we found the need to do a tidy up... All we want to keep are the classes we actually use, and there are hundreds if not thousands of classes within our CSS files, so we turned to JavaScript and ChatGPT (for us this is where AI really comes in useful). This gave us the following script:
(function() {
// Create a set to store unique class names
const classSet = new Set();
// Get all elements in the document
const allElements = document.querySelectorAll('*');
// Loop through each element and collect class names
allElements.forEach(element => {
const classList = element.classList;
classList.forEach(className => classSet.add(className));
});
// Convert the set to an array and sort it
const classArray = Array.from(classSet).sort();
// Create a container for the list
const listContainer = document.createElement('div');
const list = document.createElement('ul');
// Remove bullet points by setting the style
list.style.listStyleType = 'none'; // No bullet points
// Append class names as list items
classArray.forEach(className => {
const listItem = document.createElement('li');
listItem.textContent = className;
list.appendChild(listItem);
});
listContainer.appendChild(list);
document.body.appendChild(listContainer);
// Style the list for better visibility and to ensure it's above the page
listContainer.style.position = 'fixed';
listContainer.style.top = '10px';
listContainer.style.right = '10px';
listContainer.style.backgroundColor = 'white';
listContainer.style.padding = '10px';
listContainer.style.border = '1px solid #ccc';
listContainer.style.zIndex = '9999'; // High z-index to be above other elements
})();
Now all we need to do is paste this in to the Developer Console in Chrome (typing, allow paste, first) once the page you want to inspect has loaded, and hit Enter!
Which in our case is incredibly useful as now we'll only keep these classes and delete the clutter!
Hope someone else finds this helpful so hence the reason for sharing it...