MT IT
  • Introduction
  • KEEP IN MIND!!
  • 1️⃣1st month
    • Week 1
      • HTML/CSS
        • HTML
          • HTML Dasar
          • HTML Layouting
          • Learn More
            • Semantic HTML
            • Tables
            • Videos
            • Images
        • CSS
          • CSS Dasar
      • Weekly Review
    • Week 2
      • Bootstrap
        • Tutorial Bootstrap 5
      • Git & Github
      • Responsive
        • Responsive with Bootstrap 5
      • Weekly Review
    • Week 3
      • Javascript
        • Introduction to Javascript
          • What is JavaScript?
          • Brief History of JavaScript
          • How To Add JavaScript to HTML
        • All About Variables
          • Variables
          • Naming JavaScript Variables
          • JavaScript Naming Conventions
          • JavaScript Scope
        • Datatypes
          • What are data types?
          • Primitives and objects
          • Primitive data types
          • Object data types
          • TypeOf Operator
      • Weekly Review
    • Week 4
      • Javascript
        • Data Structures
          • Keyed Collections
          • Indexed collections
        • Equality Comparisons
        • Loops and Iterations
          • The for loop
          • do…while statement
          • while statement
      • Weekly Review
    • Monthly Review
  • 2️⃣2nd Month
    • Week 5
      • Javascript
        • Expressions and Operators
          • Basic operators, maths
          • Assignment operators
          • Comparison operators
          • Logical operators
          • String operators
          • Conditional (ternary) operator
          • Comma operator
        • JavaScript Function
        • Arrow function expressions
        • Built in functions
      • REST - Representational State Transfer
        • API - Application Programming Interface
        • Fetching data from the server
        • The Fetch API
        • Cross-Origin Resource Sharing (CORS)
      • Weekly Review
    • Week 6
      • DOM (Document Object Model)
        • DOM tree
        • Selecting elements
          • getElementById()
          • getElementsByName()
          • querySelector()
        • Manipulating elements
          • createElement()
          • appendChild()
          • textContent
        • Working with Attributes
          • Understanding Relationships Between HTML Attributes & DOM Object’s Properties
          • setAttribute()
          • getAttribute()
          • removeAttribute()
          • hasAttribute()
        • Manipulating Element’s Styles
          • JavaScript Style
          • getComputedStyle()
          • className
          • classList
          • Getting the Width and Height of an Element
        • Working with Events
          • JavaScript Events
          • Handling Events
          • Page Load Events
          • onload
          • Mouse Events
          • Keyboard Events
          • Scroll Events
          • scrollIntoView
      • React JS
        • Getting Started
        • Components Basics
          • Introducing JSX
          • Writing Markup with JSX
          • React Function Components
          • Props vs State
            • State: A Component's Memory
            • How to use Props in React
      • Working with APIs - 1
        • XMLHttpRequest
        • Fetch
      • Weekly Review
    • Week 7
      • Javascript
        • Asynchronous JavaScript
          • Asynchronous JavaScript For Dummies
            • (Pt1): Internals Disclosed!
            • (Pt2): Callbacks
            • (Pt3): Promises
            • (Pt4): Async/Await
        • Callback
        • Promises
          • Promises Basics
          • Promises Chaining
          • Promises Error Handling
        • Async/await
          • async function
        • Tutorial – Learn Callbacks, Promises, & Async/Await in JS by Making Ice Cream
      • React JS
        • Rendering
          • Conditional Rendering
          • Lists and Keys
          • Render Props
        • Hooks
          • useState
          • useEffect
      • Working with APIs - 2
        • Axios
      • React Router Dom
      • Weekly Review
    • Week 8
      • React JS
      • Responsive
      • Chakra UI
      • Firebase
        • Firebase Authentication
      • Weekly Review
    • Monthly Review
  • 3️⃣3rd month
    • Week 9
      • React JS
      • Chakra UI
      • Firebase
      • Axios
      • Weekly Review
    • Week 10
      • React JS
      • Boilerplate
      • Weekly Review
    • Week 11
      • Projects
      • Weekly Review
    • Week 12
      • Projects
      • Weekly Review
    • Project Review
  • 🏁FINAL REVIEW
  • 👇!! Learn More Below !!
  • 🥸Frontend Stack
    • 💻Web Dev
      • React JS
        • Reactstrap
        • React Icons
        • React Router Dom
      • Chakra UI
    • 📱Mobile Dev
      • React Native
        • Introduction
        • Page 1
      • Expo
      • Nativebase
    • 🎽CSS
      • Tailwind
      • Bootstrap
  • ☕Backend Stack
    • Node JS
    • Firebase
      • Authentication
      • Firestore
      • Storage
      • Hosting
      • Cloud Function
      • Emulators
      • RTDB
      • FCM
    • Google Cloud Platform
      • AppEngine
      • Big Query
      • Cloud Functions
      • Cloud Run
      • Cloud Scheduler
      • Cloud SQL
      • Logging
    • Object Relational Mapping (ORM)
      • Sequelize
    • MongoDB
      • MongoDB Realm
    • MySQL
      • Introduction
  • 🦸Fullstack
    • NEXT JS
    • LARAVEL
  • 📦Package
    • Middleware
      • Express JS
    • HTTP client
      • AXIOS
    • 📊Chart
      • Chart.js
      • JSCharting
      • React Google Chart
    • ⏳Date & Time
      • Moment JS
      • Day JS
    • 👨‍💻WYSIWYG Editor
      • Quill JS
      • Slate JS
Powered by GitBook
On this page
  • Introduction to JavaScript getComputedStyle() method
  • JavaScript getComputedStyle() examples
  • Summary
  1. 2nd Month
  2. Week 6
  3. DOM (Document Object Model)
  4. Manipulating Element’s Styles

getComputedStyle()

PreviousJavaScript StyleNextclassName

Last updated 1 year ago

Introduction to JavaScript getComputedStyle() method

The getComputedStyle() is a method of the object, which returns an object that contains the computed style an element:

let style = window.getComputedStyle(element [,pseudoElement]);
Code language: JavaScript (javascript)

Parameters

The getComputedStyle() method accepts two arguments:

  • element is the element that you want to return the computed styles. If you pass another node type e.g., Text node, the method will throw an error.

  • pseudoElement specifies the pseudo-element to match. It defaults to null.

For example, if you want to get the computed value of all the CSS properties of a link with the hover state, you pass the following arguments to the getComputedStyle() method:

let link = document.querySelector('a');
let style = getComputedStyle(link,':hover');
console.log(style);
Code language: JavaScript (javascript)

Note that window is the global object, therefore, you can omit it when calling get the getComputedStyle() method.

Return value

The getComputedStyle() method returns a live style object which is an instance of the CSSStyleDeclaration object. The style is automatically updated when the styles of the element are changed.

JavaScript getComputedStyle() examples

Let’s take some examples of using the getComputedStyle() method.

1) Simple getComputedStyle() example

Consider the following example:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>JS getComputedStyle() Demo</title>
    <style type="text/css">
        .message {
            background-color: #fff3d4;
            border: solid 1px #f6b73c;
            padding: 20px;
            color: black;
        }
    </style>
</head>
<body>

    <p class="message" style="color:red">
        This is a JS getComputedStyle() Demo!
    </p>

    <script>
        let message = document.querySelector('.message');
        let style = getComputedStyle(message);

        console.log('color:', style.color);
        console.log('background color:', style.backgroundColor);
    </script>
</body>
</html>
Code language: HTML, XML (xml)

Note that for the demonstration purpose, we mix all CSS and JavaScript with HTML. In practice, you should separate them in different files.

Output:

color: rgb(255, 0, 0)
background color: rgb(255, 243, 212)

How it works:

  • First, define CSS rules for the message class in the head section of the HTML file. The text color is black.

  • Second, declare a paragraph element whose text color is red as defined in the inline style. This rule will override the one defined in the head section.

  • Third, use the getComputedStyle() method to get all the computed style of the paragraph element. The color property is red as indicated in the Console window ( rgb(255, 0, 0)) as expected.

2) The getComputedStyle() for pseudo-elements example

The following example uses the getComputedStyle() method to pull style information from a pseudo-element:

<html>
<head>
    <title>JavaScript getComputedStyle() Demo</title>
    <style>
        body {
            font: arial, sans-serif;
            font-size: 1em;
            line-height: 1.6;
        }

        p::first-letter {
            font-size: 1.5em;
            font-weight: normal
        }
    </style>
</head>
<body>
    <p id='main'>JavaScript getComputedStyle() Demo for pseudo-elements</p>
    <script>
        let p = document.getElementById('main');
        let style = getComputedStyle(p, '::first-letter');
        console.log(style.fontSize);
    </script>
</body>
</html>Code language: HTML, XML (xml)

Output:

24px

How it works:

  • First, define CSS rules for the first letter of any paragraph element in the head section of the HTML file.

  • Then, use the getComputedStyle() method to pull the computed style of the pseudo-element. The font-size of the first letter of the paragraph with the id is 24px.

Summary

  • The getComputedStyle() is a method of the window object.

  • The getComputedStyle() method returns an object that contains the computed style of an element.

2️⃣
window