1

I'm trying to capture the display css property value for an element. However, unless I set style.display value in js it doesn't work. HTML:

<div class ="dropdown slds-size_1-of-4" >
   <p>A</p>
   <p>B</p>
   <p>C</p>
</div>

CSS:

.dropdown{
    position: absolute;
    display: none;
    background: white;
}

JS: Below JS method is be called from one of the input boxes in html:

updateDropDownStyle(){
   console.log('display : '   ,this.template.querySelector('.dropdown').style.display);
}

However, the console prints nothing at all. However, if in the same method I set the element.style.display value as none and then try to console the above - it prints none. What's the issue here?

1

That's expected. The classes do not impose their values on to the style attribute of DOM element. If you want to know the style, use getComputedStyle instead:

let style = window.getComputedStyle(this.template.querySelector('.dropdown'));
console.log(style.display); // should output "none"

Demo

<template>
<div class="dropdown slds-size_1-of-4" >
   <p>A</p>
   <p>B</p>
   <p>C</p>
</div>
{classValue}

<lightning-button label="Update" onclick={updateDropDownStyle}>
</lightning-button>
</template>

import { LightningElement, track, api } from 'lwc';

export default class App extends LightningElement {
    classValue;
    updateDropDownStyle(){
        this.classValue = window.getComputedStyle(
            this.template.querySelector('.dropdown')
        ).display;
    }
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.