alex alex - 23 days ago 8
Javascript Question

How to extract computed style values from HTML elements?

I'm using the following function to get all the HTML elements with a certain computedStyle. FOr example

will produce an array with all the elements in the page that have margin left.

getCssByRule (rule) {
const elements = Array.from(document.querySelectorAll('*')).filter(e => {
return parseInt(window.getComputedStyle(e).getPropertyValue(rule)) !== 0
return elements

How to modify this function so I can also get the value of this computedValue? (e.g

Answer Source

If you want to get an Array of computed values, then you can modify your function like this:

function getCssByRule(rule) {
  const values = Array.from(document.querySelectorAll('*'))
    .filter(e => parseInt(window.getComputedStyle(e).getPropertyValue(rule)) !== 0)
    .map(e => window.getComputedStyle(e).getPropertyValue(rule));

  return values;

<div style="margin-left: 20px"></div>
<div style="margin-left: 19px"></div>
<div style="margin-left: 18px"></div>