← Back to all snippets
JAVASCRIPT

Get an Element's Final Computed CSS Styles

Learn to accurately retrieve the final, calculated values of any CSS property for a DOM element, including inherited and cascaded styles, using `window.getComputedStyle()` for precise styling insights.

/**
 * Retrieves the final computed CSS style value for a given property of an element.
 * @param {HTMLElement} element - The target DOM element.
 * @param {string} propertyName - The CSS property name in camelCase (e.g., 'backgroundColor', 'fontSize').
 * @returns {string} The computed value of the CSS property.
 */
function getComputedStyleValue(element, propertyName) {
  if (!(element instanceof HTMLElement)) {
    console.error('Invalid element provided. Must be an HTMLElement.');
    return '';
  }
  if (typeof propertyName !== 'string' || propertyName.trim() === '') {
    console.error('Invalid propertyName provided. Must be a non-empty string.');
    return '';
  }

  // getComputedStyle returns a CSSStyleDeclaration object
  const computedStyles = window.getComputedStyle(element);

  // Convert camelCase to kebab-case for getPropertyValue for robustness.
  const cssPropertyName = propertyName.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, '$1-$2').toLowerCase();

  return computedStyles.getPropertyValue(cssPropertyName);
}

// Example Usage:
// <p id="myParagraph" style="color: blue; font-size: 16px; margin-left: 10px;"></p>
// const paragraph = document.getElementById('myParagraph');
//
// // In your CSS file: consistent with the problem statement
// // p {
// //   background-color: lightgray;
// //   padding: 20px;
// //   font-weight: bold;
// // }
//
// if (paragraph) {
//   console.log('Color:', getComputedStyleValue(paragraph, 'color')); // blue (from inline style)
//   console.log('Background Color:', getComputedStyleValue(paragraph, 'backgroundColor')); // lightgray (from stylesheet)
//   console.log('Font Size:', getComputedStyleValue(paragraph, 'fontSize')); // 16px (from inline style)
//   console.log('Padding:', getComputedStyleValue(paragraph, 'padding')); // 20px (from stylesheet)
//   console.log('Margin Left:', getComputedStyleValue(paragraph, 'marginLeft')); // 10px (from inline style)
//   console.log('Font Weight:', getComputedStyleValue(paragraph, 'fontWeight')); // bold (from stylesheet)
//
//   // Note: For properties like 'display', 'position', etc.
//   console.log('Display:', getComputedStyleValue(paragraph, 'display')); // block (default for p)
// }
How it works: This snippet demonstrates how to retrieve the final, 'computed' values of an element's CSS properties using `window.getComputedStyle()`. Unlike `element.style`, which only reflects inline styles, `getComputedStyle()` provides the resolved values after all stylesheets, browser defaults, and inheritances have been applied. This is crucial for accurately determining an element's actual dimensions, colors, or positions on the page, especially for debugging or building layout-dependent JavaScript logic. The function converts camelCase property names to kebab-case for robust `getPropertyValue` usage.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs