Skip to content Skip to sidebar Skip to footer

Can I Print A Css Style Property To The Console Using Javascript?

Got another basic question that I couldn't seem to find the answer for online. I can change the CSS property of an element easily using javascript, document.getElementById('Examp

Solution 1:

You can use getComputedStyle

let elem = document.getElementById('test');
let ht = window.getComputedStyle(elem, null).getPropertyValue("height");
console.log(ht)
.test {
  height: 300px;
  width: 300px;
  border: 1px solid red;
}
<divclass="test"id="test">Test</div>

Solution 2:

Make sure you are testing with an actual element that will be returned from your selection (see example below). Otherwise your code is fine.

const elem = document.getElementById('elemId');
elem.style.height = '30px';

console.log(elem.style.height);
<divid="elemId"></div>

Solution 3:

document.getElementById("ExampleID").style.height="30px";
console.log(document.getElementById('ExampleID').clientHeight);
console.log(document.getElementById('ExampleID').offsetHeight);
<divid="ExampleID">
clientHeight includes padding.<br>
offsetHeight includes padding, scrollBar and borders.
</div>
  • clientHeight includes padding.
  • offsetHeight includes padding, scrollBar and borders.

Solution 4:

You need to check HTML part in this case.

  1. If you are setting from javascript then Your code is working fine.

  2. In case Styles defined in CSS use window.getComputedStyle()

    The window.getComputedStyle() method returns an object that reports the values of all CSS properties of an element after applying active stylesheets and resolving any basic computation those values may contain. Individual CSS property values are accessed through APIs provided by the object or by simply indexing with CSS property names.

Here is working snippet:

var divEle=document.getElementById("ExampleID");
console.log("Before:height::"+divEle.style.height);
console.log("Before:color::"+divEle.style.color);

var  heightCss = window.getComputedStyle(divEle, null).getPropertyValue("height");
var  colorCss = window.getComputedStyle(divEle, null).getPropertyValue("color");

console.log("Before:height from css::"+heightCss)
console.log("Before:color from css::"+colorCss)

functionchangeCss(){
divEle.style.height="30px";
divEle.style.color="blue";

console.log("After:height::"+divEle.style.height);
console.log("After:color::"+divEle.style.color);
}
.divClass {
  height: 40px;
  color: red;
  width: 40px;
  border: 2px solid black;
}
<divclass="divClass"id="ExampleID">test</div><div><inputtype="button"onClick="changeCss();"value="Change Css"/></div>

Post a Comment for "Can I Print A Css Style Property To The Console Using Javascript?"