Search code examples
javascripthtmlcssgoogle-chromefirefox

Is there a way to list all available css classes for a web page?


I was wondering if there is an easy way to list all available css classes loaded withing a single html page in javascript or through the developer console in chrome or firefox.

Thank you


Solution

  • There's no easy way to find all available css classes, but we can find all those being used:

    One Liner

    [...[...$$("[class]")].reduce((s, e) =>
      (e.classList.forEach(c => s.add(c)), s), new Set())].sort()
    

    Though wrapped just for readability :-)

    Explanation

    There're two shorthands used in the above one liner:

    1. $$ is a shorthand for document.querySelectorAll
    2. [...iterable] is for Array.from(iterable), see the spread syntax (...)

    And here's the expanded code:

    Array.from(                                 // 4
      Array.from(                               // 2 
          document.querySelectorAll("[class]")  // 1
      ).reduce(                                 // 3
        (s, e) => (e.classList.forEach(c => s.add(c)), s), 
        new Set()
      )
    ).sort()                                    // 5
    
    1. find all HTML elements with the class attribute, see attribute selectors
    2. use Array.from to turn the NodeList from step 1 into an Array
    3. use Array.reduce to collect the CSS classes into a Set, to remove duplicates
    4. turn the result Set from step 3 back to an Array, for sorting
    5. sort the result

    Additionally, we can use console.table() to show the result nicely:

    console.table([...[...$$("[class]")].reduce((s, e) =>
      (e.classList.forEach(c => s.add(c)), s), new Set())].sort())