Categories
JavaScript Answers

How to read individual transform style values in JavaScript?

Spread the love

Sometimes, we want to read individual transform style values in JavaScript.

In this article, we’ll look at how to read individual transform style values in JavaScript.

How to read individual transform style values in JavaScript?

To read individual transform style values in JavaScript, we can use some string and array methods.

For instance, we write:

<div style="transform: translate(10px, 20px)">
  hello world
</div>

to add a div.

Then we write:

const element = document.querySelector('div');
const styles = window.getComputedStyle(element, null);
const matrixPattern = /^\w*\((((\d+)|(\d*\.\d+)),\s*)*((\d+)|(\d*\.\d+))\)/i;
const vals = [...styles.transform.match(matrixPattern)].slice(1).filter(Boolean).map(v => +v.replace(/\D+/, ''))
console.log(vals)

to select the div with querySelector.

Then we get the styles with getComputedStyle.

Next, we call styles.transform.match with matrixPattern to get all the numbers from the CSS style value.

Then we spread the values into an array.

Next, we call slice to remove the match with all the number values in one string.

Then we call filter to remove the falsy values.

Finally, we call map with a callback to remove all non-digit characters and use + to convert the string to number.

As a result, vals is [10, 10, 10, 20, 20].

Conclusion

To read individual transform style values in JavaScript, we can use some string and array methods.

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 *