The style is set to the canvas background: #mainCanvas { background-color:green; } #mainCanvas { background-color:green; }

I'm trying to get this parameter, but the value is empty.

 zoomCtx.fillStyle = mainCanvas.style.background; 

How to fix?

  • document.getElementById ('mainCanvas') [0] .style.backgroundColor w3schools.com/jsref/prop_style_backgroundcolor.asp - Jean-Claude
  • @ Jean-Claude Thank you. does not work. Returns null. And for what [0]? - CodeGust
  • one
    pardon getElementById returns one element, the rest like getElementsByTagName is an array, so there you need an array index [0]. working example here. How to get styles written here. - Jean-Claude
  • @ Jean-Claude Save the Bo! Works! var bgc = getComputedStyle(mainCanvas).backgroundColor; (I will mark it as accepted, if you post it as an answer ..) - CodeGust

1 answer 1

getElementById returns one element, the rest, for example, getElementsByTagName is an array, so there you need an index of the array [0]. The working example is below.

 window.onload = function() { console.log(getComputedStyle(document.getElementById('myid')).backgroundColor); console.log(getComputedStyle(document.getElementsByTagName('span')[0]).backgroundColor); }; 
 div { background-color: tomato; } span { background-color: #bfa; } 
 <div id='myid'>div</div> <span>span</span> 

How to get styles written here.

Sometimes you need to work with DOM in the browser console, including getting the value of a style. This is usually done like this:

 element = document.getElementById('foo'); color = element.style.backgroundColor; 

But it works only when the element style is set to inline:

 <div style="color:red;"> 

If the style is set in CSS, then element.style.backgroundColor will not return anything. To make it work, you need to request calculated styles:

 element = document.getElementById('foo'); color = window.getComputedStyle(element).backgroundColor;