JavaScript access CSS class by its name?
No, you can't access them by the selector - it's a simple list. You first had to build an index for it:
// assuming those are the right rules (ie from the right stylesheet)
var hui = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
var styleBySelector = {};
for (var i=0; i<hui.length; i++)
styleBySelector[hui[i].selectorText] = hui[i].style;
// now access the StyleDeclaration directly:
styleBySelector[".myclass"].color = "#ff0000";
Of course this is not a fool-proof method, there could be
- multiple selectors like
.myClass, .myOtherClass
- multiple occurences of one selector (though it doesn't matter, the last declaration overwrites previous styles anyway)
and instead of blindly assigning the color
property you first should check for existence of the declaration.
How to get CSS class property in Javascript?
For modern browsers you can use getComputedStyle
:
var elem,
style;
elem = document.querySelector('.test');
style = getComputedStyle(elem);
style.marginTop; //`20px`
style.marginRight; //`20px`
style.marginBottom; //`20px`
style.marginLeft; //`20px`
margin
is a composite style, and not reliable cross-browser. Each of -top
-right
, -bottom
, and -left
should be accessed individually.
fiddle
Find definition of CSS class in external stylesheet
If you're using the Chrome inspector (right click page, inspect element), highlight the line and look to the right. It should show the CSS class and any rules that are used, and a link to the CSS file.
How to get a style attribute from a CSS class by javascript/jQuery?
I wrote a small function that traverses the stylesheets on the document looking for the matched selector, then style.
There is one caveat, this will only work for style sheets defined with a style tag, or external sheets from the same domain.
If the sheet is known you can pass it in and save yourself from having to look in multiple sheets (faster and if you have colliding rules it's more exact).
I only tested on jsFiddle with some weak test cases, let me know if this works for you.
function getStyleRuleValue(style, selector, sheet) {
var sheets = typeof sheet !== 'undefined' ? [sheet] : document.styleSheets;
for (var i = 0, l = sheets.length; i < l; i++) {
var sheet = sheets[i];
if( !sheet.cssRules ) { continue; }
for (var j = 0, k = sheet.cssRules.length; j < k; j++) {
var rule = sheet.cssRules[j];
if (rule.selectorText && rule.selectorText.split(',').indexOf(selector) !== -1) {
return rule.style[style];
}
}
}
return null;
}
example usage:
var color = getStyleRuleValue('color', '.foo'); // searches all sheets for the first .foo rule and returns the set color style.
var color = getStyleRuleValue('color', '.foo', document.styleSheets[2]);
edit:
I neglected to take into consideration grouped rules. I changed the selector check to this:
if (rule.selectorText.split(',').indexOf(selector) !== -1) {
now it will check if any of the selectors in a grouped rules matches.
How do you read CSS rule values with JavaScript?
Adapted from here, building on scunliffe's answer:
function getStyle(className) {
var cssText = "";
var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
for (var x = 0; x < classes.length; x++) {
if (classes[x].selectorText == className) {
cssText += classes[x].cssText || classes[x].style.cssText;
}
}
return cssText;
}
alert(getStyle('.test'));
Get all CSS properties for a class or id with Javascript/JQuery
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';}
Related Topics
How to Zoom into a Web Page Like Ie or Firefox Do, Using Programming
Safari Bug :First-Child Doesn't Update Display:Block When Items Are Removed with Js
Very Simple JavaScript/Jquery Example: Unexpected Evaluation Order of Instructions
Wrap Text Inside Fixed Div with CSS or JavaScript
Render Closing Tag Conditionally in Order to Emulate Calendar Behavior
Style the Nth Letter in a Span Using CSS
CSS Not Being Applied to Document.Write Text
Sticky Header Flickering on Safari Desktop Only When Anchor Scrolling
How to Force Jquery to Center an Element When It Is Dragged to and Snapped to Another Container
How to Calculate Angle of Rotation to Make Width Fit Desired Size in Perspective Mode
Make a Div Scroll When I Reach a Certain Point
Does the JavaScript Onclick Event Not Work on <Select> <Option>'S
Getting Absolute Position of an Element Relative to Browser
Countdown Timer 'Delays' When Tab Is Inactive
Angular 2 - How to Dynamically Change an Entire CSS Stylesheet Based on Url Queryparams