Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 CSS instead of via the element? Is JavaScript particularly can't read the css style 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>
like image 911
Ramesh Rajendran Avatar asked Jun 01 '18 14:06

Ramesh Rajendran


People also ask

What does element style do?

element. style in DevTools refers to inline styles applied to that element. Inline style will take precedence over any style you apply via style sheet. That is why your declaration is being crossed out.

What is empty CSS?

The :empty CSS pseudo-class represents any element that has no children. Children can be either element nodes or text (including whitespace). Comments, processing instructions, and CSS content do not affect whether an element is considered empty.

Is HTML element empty?

HTML elements with no content are called empty elements. <br> is an empty element without a closing tag (the <br> tag defines a line break). Empty elements can be "closed" in the opening tag like this: <br />. HTML5 does not require empty elements to be closed.


1 Answers

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>
like image 107
Chiller Avatar answered Oct 03 '22 00:10

Chiller