Tutorials Books Videos Forums

Change the theme! Search!
Rambo ftw!

Customize Theme


Color

Background


Done

Inspecting an Element's Style Values using JS

by kirupa   |   16 August 2016

How your HTML elements look is something that has fascinated people for centuries. The reason is that there is a whole lot more going on than what you see on screen. Your HTML elements are affected by CSS in a variety of complex ways. You have style rules (and media queries, and calc() expressions, !important tags, the cascade, etc.), inline styles, styles automatically set by your browser, and a whole lot more that can influence the styles that get applied and what your elements look like.

While how your elements manage to look the way they do is an important part of defining your UI, chances are you care less about that when inspecting their styling using JavaScript. When you are inspecting an element's styles, you just want to know things like how tall the element is, whether it is visible or not, where it is located, etc. You usually don't care about all of the intermediate styling states your element might be in. All you care about is an element's final appearance and the various values your CSS properties store to represent this final appearance. To help you out with this, you have the getComputedStyle method.

In this short tutorial, we are going to look at the getComputedStyle method and all of the important stuff you need to know about using it.

Onwards!

Meet getComputedStyle

The getComputedStyle method allows you to get the computed style value of an element. The computed style value is the final style value applied on an element after all style-related shenanigans that impact your element's appearance have been figured out, said, and done.

The way you use this method is as follows:

var style = window.getComputedStyle(element);

The getComputedStyle method lives on our window object, and it takes one argument: the element whose styles you wish to inspect. What gets returned is a CSSStyleDeclaration object that you can call getPropertyValue on and pass in the name of the CSS property whose value you would like to inspect.

For example, this would be what examining the height of an element would look like:

var blah = style.getPropertyValue("height");

What gets returned is the computed height value. One thing to note is that the CSS property you pass in is not the JavaScript-equivalent variant of the property name. It is the actual property name as it would look in CSS. For example, this is what inspecting the CSS background-color property would look like:

var blah = style.getPropertyValue("background-color");

This property won't look like backgroundColor like it would on the style object that pretty much every DOM element carries around. Pretty straightforward, right?

An Example

In the previous section, you got the gist of how to use getComputedStyle to get the computed style value. Let's take what we've learned and put it all together with an example.

Take a look at the following markup:

<!DOCTYPE html>
<html>

<head>
  <title>Blah!</title>

  <style>
    body {
      padding: 50px;
    }
    .circle {
      background-color: rgb(0, 186, 255);
      width: 200px;
      height: 200px;
      border-radius: 50%;
    }
  </style>
</head>

<body>
  <div class="circle"></div>

  <script>
    // do something
  </script>
</body>

</html>

If you put all of this in a new HTML document and preview what you have in your browser, you'll see a totally awesome blue circle displayed:

To access our circle's CSSStyleDeclaration object, place the following inside your script region:

var myCircle = document.querySelector(".circle");
var style = window.getComputedStyle(myCircle);

From here, you have the ability to use getPropertyValue and pass in any CSS property value that you'd like the get the computed value of. For example, this is us trying to figure out what our circle's border radius would be:

var borderRadius = style.getPropertyValue("border-radius");
console.log(borderRadius); // 50%

Pretty straightforward, right? Now, for various reasons, you may be interested in figuring out the value of all style properties and their computed values on a particular element. The way you can do that is by using this little function:

function getAllComputedStyles(element) {
  var styles = window.getComputedStyle(element);

  for (var i = 0; i < styles.length; i++) {
    var style = styles[i];

    // logs all of the styles and their property values
    console.log(style + ": " + styles.getPropertyValue(style));
  }
}

This function goes through all CSS properties that it can find on our CSSStyleDeclarationObject and prints the property and its value to the console. To use it, simply call getAllComputedStyles with a DOM element as its argument. That's it. Here is an example of what our Console looks like when we call this function:

You should modify this function for your particular need to do something useful...or more useful than what is shown here :P

Conclusion

Conceptually, figuring out a style property's value seems like risky business because of all the variables and inputs involved. Fortunately, your browser takes care of all that. For inspection purposes, all you need to know is the final value, and that is what the getComputedStyle method excels at giving you. Now, before we wrap this all up, you may be wondering what purpose the style object on DOM elements serves when you have something really flexible and superior like getComputedStyle in your midst. You've probably seen it a bunch, and it is one of the most common ways you have for reading and setting CSS style properties on an element:

var myCircle = document.querySelector(".circle");
myCircle.style.backgroundColor = "#EEE";

console.log(myCircle.style.fontSize); // display the font-size value

There is one big difference. The style object pertains only to an element's inline style. You can't read style values set using anything but an inline approach. Using this approach for our earlier example would have failed, for all of our circle's styling came from a style rule:

.circle {
  background-color: rgb(0, 186, 255);
  width: 200px;
  height: 200px;
  border-radius: 50%;
}

So, reading style values doesn't work very well. On the flip side, setting a style using the style object is a different story. Because of the greater importance inline styles get relative to other styling approaches, setting a CSS property via the style object is the equivalent of taking a blunt hammer to something fragile...like butter. That terrible analogy aside, you can easily override any existing style on an element by setting a style via the style object. That's what I'm getting at. I think.

Just a final word before we wrap up. If you have a question and/or want to be part of a friendly, collaborative community of over 220k other developers like yourself, post on the forums for a quick response!

Kirupa's signature!

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends

:: Copyright KIRUPA 2024 //--