3

How can I compute the used style values of an element (instead of the computed style values)? In this code, I am using getComputedStyle, and the output says that subdiv has computed display = block, eventhough it is not displyed. How can I modify the code to get a used display = none, as everybody would expect?

<html><body>
test
<div id="maindiv" style="display: none">
 maindiv
  <div id="subdiv" style="display: block">subdiv</div>
</div>
<script>
alert(window.getComputedStyle(document.getElementById("subdiv")).display)
</script>
</body></html>

From https://developer.mozilla.org/en-US/docs/Web/CSS/used_value

"used value" vs "computed value"

CSS 2.0 defined only computed value as the last step in a property's calculation. Then, CSS 2.1 introduced the distinct definition of used value. An element could then explicitly inherit a width/height of a parent, whose computed value is a percentage. For CSS properties that don't depend on layout (e.g., display, font-size, or line-height), the computed values and used values are the same. The following are the CSS 2.1 properties that do depend on layout, so they have a different computed value and used value: (taken from CSS 2.1 Changes: Specified, computed, and actual values):

David Portabella
  • 12,390
  • 27
  • 101
  • 182
  • 1
    What you are seeing is what is expected, `display` is not inherited. If I'm in a box and I'm dancing but you cannot see into the box; does that mean I'm not dancing? No. You'll want to check other DOM properties to see if the element is visible, see [this SO post](https://stackoverflow.com/questions/19669786/check-if-element-is-visible-in-dom). – hungerstar Dec 11 '17 at 17:24
  • I like the question but in a real world scenario I suspect it would be better to figure it out on a per usage base to be clear what you need. I can't think of some logic where this would work the same for many properties and so it would become very hard to understand all exceptions. You can already figure out if an element is visible at all, you can figure out an elements its position to the viewport, you can figure out an elements inherited value, etc. – René Dec 11 '17 at 17:28
  • "You can already figure out if an element is visible at all". how? – David Portabella Dec 11 '17 at 17:32
  • @DavidPortabella [see the link in my comment](https://stackoverflow.com/questions/19669786/check-if-element-is-visible-in-dom). – hungerstar Dec 11 '17 at 17:36
  • getComputedStyle() does return used values in many cases - its name is misleading and there are historical reasons behind that. CSS does not appear to define the used value of display when the element has an ancestor that has display: none, though. (MDN's claim that the computed value and used value are the same for the display property, while I believe it, is unsourced - the spec does *not* mention this at all.) – BoltClock Dec 11 '17 at 18:06

0 Answers0