1

My CSS

.h1-modified{
    color: green;
}

My JavaScript file

var h1Modified = [HERE IS SOME CODE MISSING];

I want to store the color of the html class .h1-modified in the JavaScript variable h1Modified.

If it works alert(h1Modified); outputs green.

PROBLEM: .h1-modified isn't assigned to any HTML element. I have to access the CSS file directly.

2 Answers 2

2

So if you want to read a CSS property.. I don't think you can read it directly from CSS, but you can read it from an element that has this class

const tag = document.getElementById('my_id');
const styles = window.getComputedStyle(tag);
const tagColor = style.getPropertyValue('color');

You can read more about it here: CSSStyleDeclaration.

Or you could just read a color from an elemenet

const color = document.getElementById("tag").style.color;

PS: Oh, you need to parse CSS file? Well, parsers are available in any language, JavaScript is one of them. Take a look at JSCSSP. It can parse CSS files, but keep in mind that this parsed file won't necessarily be the same that is used to render the website. Or that styles found in the file will be applied to your HTML tags.

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

4 Comments

I don't want to modify CSS (class) from JavaScript, I just want to read it.
@Sr.Schneider Do you want to read a color of a HTML element or CSS class?
I have to access the CSS file via JavaScript. Looks like this isn't possible.
@Sr.Schneider Please see my editted answer. Consider accepting it if it solved your problem, or tell me what I can do to improve it.
0

I know someone already has answered it. But here is a Jquery version:

$('#id').css('color', 'blue'); //To change

to store as var:

var x = $('#id').css('color');  //will return the colour

reference:

http://api.jquery.com/css/

4 Comments

Is something like var x = $('#id').css('color'); available in plain JS?
try this : var x = document.getElementById("myId").style.color I think it will do the job
The question asked for JavaScript not jQuery
read the answer again and then read the comments before commenting

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.