Yes, you can create a simple JavaScript code snippet that you can paste into the browser console to find out which CSS file is styling elements with a specific class name. Here's how you can do that:
- Open your browser's console (usually by right-clicking on the page, selecting "Inspect," and navigating to the "Console" tab).
- Paste the following code into the console:
function findStylesheetByClass(className) {
const elements = document.querySelectorAll(`.${className}`);
const stylesheets = [...document.styleSheets];
const matchedStylesheets = stylesheets
.filter(sheet => sheet.cssRules)
.flatMap(sheet => {
try {
return [...sheet.cssRules].filter(rule => rule.selectorText && rule.selectorText.includes(`.${className}`))
.map(rule => ({
rule: rule.cssText,
href: sheet.href
}));
} catch (e) {
// Ignoring cross-origin stylesheets that cannot be accessed
return [];
}
});
if (matchedStylesheets.length === 0) {
console.log(`No styles found for class: .${className}`);
return;
}
console.log(`Styles for class .${className}:`);
matchedStylesheets.forEach(({ rule, href }) => {
console.log(`Rule: ${rule} | Source: ${href}`);
});
}
// Example usage:
findStylesheetByClass('your-class-name'); // Replace 'your-class-name' with the class you want to check
How it Works:
- This function,
findStylesheetByClass, takes a class name as an argument.
- It queries all elements in the document with that class name and collects all stylesheets applied to the document.
- For each stylesheet, it checks its
cssRules and looks for any rules that apply to the specified class.
- It then logs the CSS rules along with the stylesheet's
href (the URL of the CSS file) to the console.
Example Usage:
After you paste the code into the console, you can call the function by replacing 'your-class-name' with the class name you're interested in. For example:
findStylesheetByClass('my-class');
Notes:
- This code might not work for stylesheets hosted on a different origin due to CORS (Cross-Origin Resource Sharing) restrictions; those stylesheets cannot be accessed directly through JavaScript.
- It will only find styles defined in external stylesheets; styles defined in
<style> tags or inline styles will not be reported by this snippet.