JavaScript window.getComputedStyle() Method

You are Here:

JavaScript window.getComputedStyle() Method

The window.getComputedStyle() method returns an object containing the values of all CSS properties of an element, after applying active stylesheets.

Example

HTML Online Editor
<!DOCTYPE html> <html> <head> <style> #test{ color: red; } </style> </head> <body> <h2 id="test">Hello World!</h2> <p id="point"></p> <script> var x = document.getElementById("point"); var y = document.getElementById("test"); var z = window.getComputedStyle(y, null); var txt = z.getPropertyValue("color"); x.innerHTML = "h2 color is "+ txt; </script> </body> </html>

Syntax

window.getComputedStyle(elem, pseudoElem)

Parameter Values

ValueTypeExplanation
elemRequiredSpecifies the Element for which to get the computed style.
pseudoElemOptionalA string specifying the pseudo-element to match.

Applying Pseudo Element

In the following example, we will apply the pseudo element (first-letter).

Example

HTML Online Editor
<!DOCTYPE html> <html> <head> <style> #test::first-letter{ color: red; } </style> </head> <body> <h2 id="test">Hello World!</h2> <p id="point"></p> <script> var x = document.getElementById("point"); var y = document.getElementById("test"); var z = window.getComputedStyle(y, "first-letter"); var txt = z.getPropertyValue("color"); x.innerHTML = "h2 color is "+txt; </script> </body> </html>

Get All CSS Properties

Example

HTML Online Editor
<!DOCTYPE html> <html> <head> <style> #test{ color: red; } </style> </head> <body> <h2 id="test">Hello World!</h2> <p id="point"></p> <script> var x = document.getElementById("point"); var y = document.getElementById("test"); var z = window.getComputedStyle(y, null); var txt = ""; for(i = 0; i < z.length; i++){ cssProp = z.item(i) txt += cssProp +" : "+ z.getPropertyValue(cssProp) +"<br>"; } x.innerHTML = txt; </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author