Get CSS styles from Typescript or Javascript
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-
- First get all the button elements by querySelectorAll. It returns a NodeList<Element> (Node list of elements).
- 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.
- 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”>