2

let's imagine I've declared some styles (either directly on my html document or by external css file(s)):

<style>
.Red { background-color: red; }
.Green { background-color: green; }
.Blue { background-color: blue; }
</style>

In my javascript code I would like to list all available styles in Array or any other form

function getAvailableStyleNames(){
  return ["Red", "Green", "Blue"]; // Dummy code. the answer would go here...
}

Thanks!

lviggiani
  • 5,824
  • 12
  • 56
  • 89

1 Answers1

6

Here is the function that you want :

CSS

.Red { background-color: red; }
.Green { background-color: green; }
.Blue { background-color: blue; }

JS

function PrintRules() {
    var rules = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
    var rulesDiv = document.getElementById("rules");
    for(var x=0;x<rules.length;x++) {
        rulesDiv.innerHTML += rules[x].selectorText + "<br />";
    }
}

HTML

<input onclick="PrintRules()" type="button" value="Print Rules" /><br />
Rules:
<div id="rules"></div>
Maen
  • 10,603
  • 3
  • 45
  • 71
Akram Fares
  • 1,653
  • 2
  • 17
  • 32
  • That's great! thank you very much! Will it work in IE10 too? (I don't have a Windows PC here to test) I guess I can iterate through styleSheets to get all styles also declared in external linked css files – lviggiani Jul 23 '13 at 14:47
  • Will it work in IE10 too? (I don't have a Windows PC here to test) I guess I can iterate through styleSheets to get all styles also declared in external linked css files – lviggiani Jul 23 '13 at 14:49
  • It's the same thing for me here ... You can host the page and test it here http://netrenderer.com/ – Akram Fares Jul 23 '13 at 14:49