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.
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.
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:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.