Why element.style always return empty in JS?
element.style returns the inline style used in html document and since the style is not set directly in html you will get and empty value
What you are looking for is the computedStyle which will returns the style that is applied to the element
console.log(window.getComputedStyle(document.getElementById('test')).display)
#map {
display: block;
align-content:center;
}
<div id="test">test</div>
The HTMLElement.style property is used to get as well as set the inline style of an element. While getting, it returns a CSSStyleDeclaration object that contains a list of all styles properties for that element with values assigned for the attributes that are defined in the element's inline style attribute.
HTMLElement.style
console.log(document.getElementById('test').style.display)
#map {
display: block;
}
<div id="test">test</div>
In this above snippet, your HTML element doesn't have a style
attribute. So, your JavaScript object's style property doesn't contain a display property either. So, console.log(document.getElementById('test').style.display)
doesn't print anything.
console.log(document.getElementById('test').style.display)
<div style="display:none" id="test">test</div>
In the above snippet, your HTML element has a style attribute with "display". So your JavaScript object contains a style property that contains a display property. That's why console.log(document.getElementById('test').style.display)
prints 'none'
The DOM API provides a way to manipulate HTML element as JavaScript objects. Your HTML elements may have classes defined in their class
attribute that grant them CSS properties, but your JavaScript object only contains the class names in its className
property. The DOM API doesn't parse the CSS to update the JavaScript HTMLElements.