Get CSS Styles Applied to an Element in JavaScript

OpenJavaScript 0

Last updated: December 28, 2023.

Consider the following HTML markup:

<div class="content">
  <p>The content</p>
</div>

With the following styles applied via a CSS stylesheet:

.content {
  width: 200px;
  height: 200px;
  background-color: #a52a2a;
}

In JavaScript, the styles applied to the <div> with the class name of content can be accessed using the globally available getComputedStyle() function.

The function accepts a HTML element and returns all its styling in object format:

// Select element to retrieve styling from:
const contentDiv = document.querySelector('.content');

// Pass element into getComputedStyle()
const contentDivStyles = getComputedStyle(contentDiv);

console.log(contentDivStyles); 
// CSSStyleDeclaration {...}

Individual CSS styles can be accessed by querying properties on the CSSStyleDeclaration object using camel-case sytnax:

// ...after code abode:

console.log(contentDivStyles.width); // 200px
console.log(contentDivStyles.height); // 200px
console.log(contentDivStyles.backgroundColor); // rgb(165, 42, 42)

Inline styles

For inline styles, it is not necessary to run CSSStyleDeclaration.

Instead, these can be accessed on the style property of using camel case syntax.

For example, consider the following HTML:

<div class="content" style="width: 200px; background-color: #a52a2a;">
  <p>The content</p>
</div>

With JavaScript, the inline styles applied to the <div> can be accessed directly on the element's style property:

const contentDiv = document.querySelector('.content');

console.log(contentDiv.style.width); // 200px
console.log(contentDiv.style.backgroundColor); // rgb(165, 42, 42)