Css: how to access a value that is not used by an element?

I have a DIV that gets its height from a CSS class in a separate stylesheet. But this height sometimes changes in Javascript. Can I read CSS height directly from the stylesheet without creating a new element?

+4
source share
3 answers

You can do something like this:

var myDiv = $("#myId"); alert('initial height from css is: ' + myDiv.css("height")); myDiv.css("height","50px"); alert('height modified by js is: ' + myDiv.css("height")); // store modified height value var height = myDiv.css("height"); // set height to an invalid value myDiv.css("height",""); alert('height is now retrieved from css again: ' + myDiv.css("height")); // restore height value myDiv.css("height",height); 

I created an example on jsfiddle.net, you can view it here .

+3
source

This is possible provided that the change in height is initiated by a known cause.

First save the current string height / class names. Then reset the class / height property. Then use the window.getComputedStyle method to read the current height. Finally, restore the class / height properties. Suppose class names do not need to be deleted because the height is changed only by setting the built-in property of height . Then:

 function getCSSheight(elem) { var style = window.getComputedStyle(elem, null); return style.getPropertyValue("height"); //Returns 222px; // Optionally: Use parseFloat to convert the `22px` to `22`. } 
+2
source

No, you cannot read any properties from CSS.

You can create some kind of API that allows you to modify your CSS files directly from JavaScript, than you can change the height in the CSS file instead of applying style to the element.

+1
source

Source: https://habr.com/ru/post/1382165/


All Articles