White Maskers White Maskers - 1 month ago 11
CSS Question

How can I read a CSS property value using Javascript?



function displayWidth(){

document.getElementById("navbar").className = "navbar-after-click";
alert(document.getElementById("navbar").style.width);

}

#navbar {
background-color:red;
height:200px;
}
.navbar{
width :220px;
}
.navbar-after-click{
width:60px;
}

<html>
<body>
<div id="navbar" class="navbar">

</div>
<button type="button" onclick="displayWidth();">show width </button>
</body>
</html>





I'm not too familiar with Javascript, that is why I am asking this question. In the above code I tried to alert a CSS property value using Javascript. But it doesn't alert any value as I expected. Is there any wrong with my code? How can I fix this?

Answer

Use getComputedStyle

Plknr Demo:

http://plnkr.co/edit/BQEdwqeZgZ1Nc02ZeAzQ?p=preview

Stack Snippet:

function displayWidth(){
  
  document.getElementById("navbar").className = "navbar-after-click";
  var nav = document.getElementById("navbar");
   var navWidth = window.getComputedStyle(nav,null).getPropertyValue("width");
  alert(navWidth);
  
  }
#navbar {
  background-color:red;
  height:200px;
  }
.navbar{
   width :220px;
}
.navbar-after-click{
    width:60px;
}
<html>
  <body>
    <div id="navbar" class="navbar">
      
    </div>
    <button type="button" onclick="displayWidth();">show width </button>
  </body>
</html>