0

I understand how document.querySelector works in order to retrieve a css element within the .html file itself, but how do I retrieve things from my .css file?

Example of my .css file:

canvas {
background-color: DarkBlue;
}

And what I have in my .js file (which I know would only work for HTML, so I am wondering the equivalent for CSS, I do not want to style in the HTML file, I want to keep my seperate CSS file):

var canvas = document.querySelector('canvas');
  • you want to retrieve the css properties of html element? – Manos Kounelakis Apr 22 '17 at 03:04
  • 2
    `I understand how document.querySelector works in order to retrieve a css element within the .html file itself` - clearly you don't understand what querySelector does - it retrieves a HTML element using a css selector - not a "css element" - if you want to get the "computed" css for an element, use `getComputedStyle` or `getDefaultComputedStyle` - see documentation to understand the difference – Jaromanda X Apr 22 '17 at 03:09
  • `css` elements, apart from pseudo-elements, don't really exist. They are still HTML elements. You are simply selecting them by their class – nicholaswmin Apr 22 '17 at 03:14

1 Answers1

0

You wouldn't want to parse a CSS file, although you could. It's far better to get the element with javascript i.e. canvas and then get the style of that element with JS.

This was previously answered very well here and provides a good function to make it a little easier: JavaScript get Styles

function getStyle(oElm, strCssRule){
    var strValue = "";
    if(document.defaultView && document.defaultView.getComputedStyle){
        strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
    }
    else if(oElm.currentStyle){
        strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
            return p1.toUpperCase();
        });
        strValue = oElm.currentStyle[strCssRule];
    }
    return strValue;
}

var elementFontSize = getStyle(document.getElementById("container"), "font-size");

Good luck.

Community
  • 1
  • 1
anthonyroberts
  • 217
  • 2
  • 10