Categories
JavaScript Answers

How to Get a CSS Property Value of an Element with JavaScript?

Spread the love

Sometimes, we may want to get a CSS property value of an element with JavaScript.

In this article, we’ll look at how to get a CSS property value of an element with JavaScript.

Use the window.getComputedStyle Method

We can use the window,getComputedStyle method to get the computed CSS styles of an element.

For instance, if we have the following HTML:

<div style='height: 300px; overflow-y: auto'>

</div>

Then we can write the following JavaScript:

const div = document.querySelector('div')
for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = i
  div.appendChild(p)
}

const style = window.getComputedStyle(div);
const height = style.getPropertyValue('height');
console.log(height)

to add some content to the div.

We have the for loop to add 100 p elements into the div with document.createElement .

Then we set the textContent of each element to add some content.

And then we call div.appendChild to add the p elements as children of the div.

Next, we call window.getComputedStyle with the div to get a style object.

And then we can get the height property with:

const height = style.getPropertyValue('height');

And height is '300px' since we set it as such in the HTML.

Use the Element’s computedStyleMap Method

Also, we can use the computedStyleMap method that comes with elements to get the styles applied to the element.

For instance, we have the following HTML:

<div style='height: 300px; overflow-y: auto'>

</div>

And we can write the following JavaScript:

const div = document.querySelector('div')
for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = i
  div.appendChild(p)
}

const style = div.computedStyleMap();
const height = style.get('height');
console.log(height)

Everything above the last 3 lines is the same as before.

Then we call div.computedStyleMap to get a style object that we can use to get the styles.

And then we have:

const height = style.get('height');

to get the CSSheight property value of the div.

This time height should be:

{value: 300, unit: "px"}

The value and unit are separate properties in the returned object.

Conclusion

There’re a few ways we can use to get the CSS properties from an element with JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *