0

I have an HTML document with a link tag in its head to a particular CSS stylesheet:

<link rel="stylesheet" href="style.css" type="text/css">

This .css file contains a particular class, like so:

.mystyle {
    color: #00c;
}

What I'm trying to do is to grab that class's color field, so that I can use it dynamically in another part of the page (for another element's background-color). Is there any way in a JavaScript program to access that information, by the name of the class? Something like this:

var myColor = document.getStyle(".mystyle").color;

Some caveats:

  1. There may or may not be other stylesheets that are also linked from this HTML document.
  2. There may or may not be any particular elements on the page that are styled with this particular class.
  3. I've already tried setting a temporary element to have the given class, and then grabbing its color field. That didn't work: the color field contains the empty string.

Thanks.

3
  • Bunch of ways to do this, depending on need. Check this out: htmlgoodies.com/html5/css/…. Note that there are more than a few questions that deal with using element.currentStyle and document.getComputedStyle(element), so this question is probably a duplicate. Commented Jan 30, 2018 at 2:11
  • jsfiddle.net/xp5r8961 from stackoverflow.com/questions/324486/… Commented Jan 30, 2018 at 2:11
  • Might very well be duplicate, but I didn't find anything after searching for several minutes. (At least, not that didn't assume that this was the only style sheet.) Thanks @Tibrogargan--that was exactly the answer I needed. I didn't know that getComputedStyle() existed. Commented Jan 30, 2018 at 2:26

4 Answers 4

1

You can get all stylesheet information using the StyleSheetList and related objects.

In the example below, I aggregate all the document's styles (i.e., inline styles, an external bootstrap stylesheet and the stylesheet provided by Stackoverflow), and retrieve the color information for the .mystyle class:

const sheets = [...document.styleSheets];
const rules = sheets.reduce((a, v) => [...a, ...v.cssRules || []], []);
const rule = rules.find(r => r.selectorText === '.mystyle');

console.log(rule.style.color);
.mystyle {
    color: #00c;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>

Sign up to request clarification or add additional context in comments.

Comments

1

It's possible to use JavaScript to read the actual CSS files themselves by scraping the DOM and extracting the relevant information. While possible, it's clunky, and I'd advise against that unless absolutely necessary. If it's required, this answer covers it pretty well.

As an alternative to scraping the header information, you could use HTMLElement.style and grab the color value, though note that this will only work for inline styles:

var span1 = document.getElementsByTagName('span')[0];
var span2 = document.getElementsByTagName('span')[1];

// Empty
console.log(span1.style.color);

// Blue
console.log(span2.style.color);
.mystyle {
    color: #00c;
}
<span class="mystyle">Text</span>
<span style="color: #00c;">Text</span>

However, a much better solution would be making use of what are known as CSS variables. These are defined in :root with a double hyphen prefix, and can be referenced with var(). This allows you to only set a colour once, and re-use it for both a color property and a background-color property, as can be seen in the following:

:root {
  --colour: #00c;
}

.a {
  color: var(--colour);
}

.b {
  background-color: var(--colour);
}
<span class="a">Text</span>
<span class="b">Text</span>

Hope this helps! :)

1 Comment

That's very cool--I didn't know there were such variables. Won't help in this project, but I'll keep it in mind for later!
0

Try window.getComputedStyle in combination with getPropertyValue.

var elem = document.getElementsByClassName("mystyle"); var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("color");

More: https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

4 Comments

Check condition 2 in the question: There may or may not be any particular elements on the page that are styled with this particular class. So you'd have to create an element first. In any case, you're not guaranteed to get the color specified in the class. It still depends on what other styles might be applied to the selected element.
I see now. Yes that is correct. You could write a script to create a hidden element with just that class applied and then use the above code to find the relevant property (as long as it isn't the property hiding it). The only concern I would have about css variables is browser compatibility but the majority support it and it is proper way of doing this.
Yeah, your suggestion is likely to work, but let's say you create a hidden <div class="mystyle"> and somwhere there's a style rule that says div: {color: green !important}, you'd still get inaccurate information.
Of course, !important is very dangerous. Your answer is preferred, just thinking of alternatives that may work for OP depending on his use case.
0

For any who might come after me:

One can indeed use window.getComputedStyle(element) on an element. However, creating your own element first (if one doesn't exist) comes with an important caveat. Firefox will properly calculate the computed style. However, Chrome (and possibly Safari too) won't calculate the style of an orphaned element that isn't part of the DOM tree. So if you go that route, be sure to add it to the tree somewhere, possibly as a hidden element.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.