0

I have this CSS property in style.css

.beatBlock {
    height: 0;
    transition: height 1s ease;
}

.beatBlock.beatBlockShow {
    height: 150px;
}

I want to be able to read the height literal value written in .beatBlockShow and retrieve the value 150 (or 150px, it doesn't matter). The problem is, I can't do the following :

let beatBlock = document.createElement('div');
beatBlock.classList = 'beatBlock';
beatBlock.classList.add('beatBlockShow');

// of course it will give me a height between 0 and 150, because of the transition property
const literalHeight = beatBlock.offsetHeight; 
console.log(literalHeight);
.beatBlock {
    height: 0;
    transition: height 1s ease;
}

.beatBlock.beatBlockShow {
    height: 150px;
}
<div class="beatBlock">
<div class="beatBlockShow"></div>
</div>

How can I do this ? Thank you

cccn
  • 929
  • 1
  • 8
  • 20
Fumée Noire
  • 93
  • 1
  • 8
  • `beatBlock.style.transition = ""`, _then_ calculate the height. – Salman A Oct 04 '19 at 11:47
  • https://css-tricks.com/an-introduction-and-guide-to-the-css-object-model-cssom/#article-header-id-8 – Scott Marcus Oct 04 '19 at 11:49
  • you can also use `document.styleSheets` , iterate over it & get the value. – Sawant Sharma Oct 04 '19 at 11:50
  • Do you need this value immediately, or will it suffice to get it after the transition has ended (you can listen to `transitionend` events on the element) – Phillip Oct 04 '19 at 11:54
  • @Phillip I need this value immediately – Fumée Noire Oct 04 '19 at 11:56
  • I found the way to solve it (sorry, cannot answer my own question yet) : ` // find needed literal CSS values literalValue = "", literalValue2 = ""; for (let styleSheet of document.styleSheets) { let allRules = styleSheet.cssRules; for (let rule of allRules) { if (rule.selectorText === '.yourClass') { literalValue = parseInt(rule.style.height, 10); } else if (rule.selectorText === '#yourId') { literalValue2 = parseInt(rule.style.height, 10); } } } ` – Fumée Noire Nov 04 '19 at 22:22

1 Answers1

1

You can append the div to your body (so that its styles can be evaluated) and then use getComputedStyle() to get the height of the element:

let beatBlock = document.createElement('div');
beatBlock.classList.add('beatBlock');
beatBlock.classList.add('beatBlockShow');

document.body.appendChild(beatBlock); // add div to DOM

const literalHeight = getComputedStyle(beatBlock).getPropertyValue('height');

console.log(literalHeight);
.beatBlock {
  height: 0;
  transition: height 1s ease;
}

.beatBlock.beatBlockShow {
  height: 150px;
}
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64