Javascript – get computed style of an element

To get computed style of an element the following approaches can be taken:

  • Vanilla javascript: window.getComputedStyle(element)
  • jQuery: .css(propName)

Example – computed style using Javascript

<style>
.box {color: lightgreen;}
</style>
<div class="box">
  <p>Hello world</p>
</div>
<pre>
</pre>
<script type="text/javascript">
  var el = document.querySelector(".box");
  var styleVal = window.getComputedStyle(el).color;
  document.querySelector("pre").innerText = "computedStyleVal=" + styleVal;
</script>
refresh

Example – computed style using jQuery

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<style>
.box {color: lightgreen;}
</style>
<div class="box">
  <p>Hello world</p>
</div>
<pre>
</pre>
<script type="text/javascript">
  var styleVal = $(".box").css("color");
  document.querySelector("pre").innerText = "computedStyleVal=" + styleVal;
</script>
refresh
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments