'Why element.style always return empty in JS?
When you define display:block in css, element.style.display is returning always empty.
console.log(document.getElementById('test').style.display)
#map {display: block;}
<div id="test">test</div>
But if you set style in that element, then we can get the style.display details.
console.log(document.getElementById('test').style.display)
<div style="display:none" id="test">test</div>
I don't want the solutions because I know SO having lot of solutions for it :
getElementById().style.display does not work
Show/Hide google maps api does not work fine
My question is different.
Inline style is not a good way of coding. So we always assign the style in CSS. But why it's showing empty while provide style property in
CSSinstead of via the element? Is JavaScript particularly can't read thecssstyle property?
you can check below, all the style properties are empty even I am providing display: block;
align-content:center;. Why?
console.log(document.getElementById('test').style)
#map {display: block;align-content:center;}
<div id="test">test</div>
Solution 1:[1]
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.
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
