getComputedStyle()
Introduction to JavaScript getComputedStyle()
method
getComputedStyle()
methodThe getComputedStyle()
is a method of the window
object, which returns an object that contains the computed style an element:
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 tonull
.
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:
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
getComputedStyle()
examplesLet’s take some examples of using the getComputedStyle()
method.
1) Simple getComputedStyle()
example
getComputedStyle()
exampleConsider the following example:
Note that for the demonstration purpose, we mix all CSS and JavaScript with HTML. In practice, you should separate them in different files.
Output:
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
getComputedStyle()
for pseudo-elements exampleThe following example uses the getComputedStyle()
method to pull style information from a pseudo-element:
Output:
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 thewindow
object.The
getComputedStyle()
method returns an object that contains the computed style of an element.
Last updated