Adam Smith
Adam Smith

Reputation: 511

Getting a field from a named CSS style in Javascript

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.

Upvotes: 0

Views: 228

Answers (4)

Adam Smith
Adam Smith

Reputation: 511

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.

Upvotes: 0

Robby Cornelissen
Robby Cornelissen

Reputation: 97120

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"/>

Upvotes: 1

Obsidian Age
Obsidian Age

Reputation: 42304

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! :)

Upvotes: 1

quinlo
quinlo

Reputation: 105

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

Upvotes: 0

Related Questions