I have this code:
<style>
#div {
height: 100px;
background-color: #A00;
}
.short {
max-height: 0px;
}
</style>
<div id="div" class="short"></div>
<script>
var div = document.getElementById("div");
var computed = window.getComputedStyle(div);
console.log(computed.height); //... I expected 100px instead of the value for max-height definition.
</script>
I know that the max-height limits the height, but how do I get the "height" definition instead of the rendered value?
We can read the CSS stylesheet rules of the document (
document.styleSheets, see MDN) and extract rules with the selector text of#divand then use the first height value. The first item should be the highest prioritized style.We iterate through all of the styles until we get a result that isn't an empty string, otherwise the function could break in the sense that another
#divstyle without aheightproperty would still be prioritized over a previously defined#divstyle with aheightproperty.Using the function provided at: https://stackoverflow.com/a/22638396/20073186
We can look specifically for the
#divstyling, and if we can't find it (or a height value), use the computed styling:And use it as such:
It's important to note that if the selector text would e.g. be
body #div, then it would go uncaught by this function. You could work around this by replacingrules.filter((rule) => rule.selectorText == selectorText)withrules.filter((rule) => rule.selectorText.endsWith(selectorText))but this could potentionally be misleading.