Is it possible to specify a class or an ID and get all the CSS rules for that particular class or ID. I don't mean an element, I want to specify a class and return all CSS for that class.
I know I can use .style
to get inline styles but I don't need inline, it has to come from the stylesheet.
Is it even possible with JS? Can it access the .css file and return a list of properties for a certain class?
Apologies for no code, it's more of a theoretical question although if someone has a function at hand, I'd be happy to study it.
Use document#styleSheets and extract all rules from all stylesheets into array. Then filter the array by the selectorText
.
Note: I've used a simple Array#includes to check if the requested selector appears in selectorText
, but you might want to create a stricter check to prevent false positives. For example the selector text .demo
can find rules for .demogorgon
as well.
const findClassRules = (selector, stylesheet) => {
// combine all rules from all stylesheets to a single array
const allRules = stylesheet !== undefined ?
Array.from((document.styleSheets[stylesheet] || {}).cssRules || [])
:
[].concat(...Array.from(document.styleSheets).map(({ cssRules }) => Array.from(cssRules)));
// filter the rules by their selectorText
return allRules.filter(({ selectorText }) => selectorText && selectorText.includes(selector));
};
console.log(findClassRules('.demo', 0));
.demo {
color: red;
}
.demo::before {
content: 'cats';
}
You can do:
window.getComputedStyle($('[your class name]')[0])
Check out https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle for more information.
来源:https://stackoverflow.com/questions/45447919/get-all-css-properties-for-a-class-or-id-with-javascript-jquery