Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript access CSS class by its name?

I have to access CSS class by name, and the code below works. However if I try hui["myclass"] or hui[".myclass"] instead of hui[0] it cannot find it.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    <style>
      .myclass {
        color: #00aa00;
      }
    </style>
    <script type="text/javascript">
        function change_class() {
          var hui = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
          hui[0].style["color"]="#ff0000"
        }
    </script>
  </head>
  <body>
    <div class="myclass" onclick="change_class()">Some Text</div>
  </body>
</html>

EDIT: I need to be able to acess as i described on line 1 i dont want to acess trough individual elements on page, but directly to stylesheet by class name.

So you all saying i cannot access to stylesheet by class name only by index?

like image 394
John Smith Avatar asked Oct 22 '12 22:10

John Smith


2 Answers

No, you can't access them by the selector - it's a simple list. You first had to build an index for it:

// assuming those are the right rules (ie from the right stylesheet)
var hui = document.styleSheets[0].rules || document.styleSheets[0].cssRules;

var styleBySelector = {};
for (var i=0; i<hui.length; i++)
    styleBySelector[hui[i].selectorText] = hui[i].style;

// now access the StyleDeclaration directly:
styleBySelector[".myclass"].color = "#ff0000";

Of course this is not a fool-proof method, there could be

  • multiple selectors like .myClass, .myOtherClass
  • multiple occurences of one selector (though it doesn't matter, the last declaration overwrites previous styles anyway)

and instead of blindly assigning the color property you first should check for existence of the declaration.

like image 153
Bergi Avatar answered Oct 17 '22 07:10

Bergi


Yes, Bergi is right:
You first have to build an index for the style list.
BUT take care:
If there is more than 1 stylesheet you first have to loop over the stylesheets. So I like to improve Bergis solution:

var styleBySelector = {};
for (var j=0; j<document.styleSheets.length; j++)   {
  var styleList = document.styleSheets[j].rules || document.styleSheets[j].cssRules;
  for (var i=0; i<styleList.length; i++)
    styleBySelector[styleList[i].selectorText] = styleList[i].style;
 }

// And then invoke or set the style you wish like this:
styleBySelector[".myStyle"].color = "#ff0000";
like image 28
Detlef Lindenthal Avatar answered Oct 17 '22 07:10

Detlef Lindenthal