Get CSS styles from Typescript or Javascript

Monir Khan
1 min readOct 1, 2020

--

Scenario: Get all visible buttons.

CSS

button.hiddenButtons{
display: none;
}
button.hiddenButtons2{
visibility: hidden;
}

Typescript / Javascript ES6

const buttons = document.querySelectorAll(‘button’);const visibleButtonArray = […buttons].filter((element) => window.getComputedStyle(element).display !== ‘none’ && 
window.getComputedStyle(element).visibility !== 'hidden'
);

Steps-

  1. First get all the button elements by querySelectorAll. It returns a NodeList<Element> (Node list of elements).
  2. Then convert it inte an array using three dots […NodeList] and use the es6 filter option that returns an array with desired values and takes away unwanted ones.
  3. In the example above, elements that does not have display = ‘none’ or visibility = ‘hidden’ will be filtered out from array

Be-aware : querySelector on style does not work in Typescript or Javascript

querySelectorAll (‘button:not([style*="display:none"])’) 

Above code may work only if you write inline css. Ex. <div style=”display: none”>

--

--

Monir Khan
Monir Khan

Written by Monir Khan

System developer, Swedish board of agriculture

No responses yet