Forum Moderators: open
I've seen many scripts for swapping from one class to another by referencing the object's id, but I want to be able to change the actual class itself.
If it is doable, how would the properties of the class be referenced?
Thank you in advance!
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Untitled</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<style type="text/css">
.testClass{font:2em Verdana,sans-serif;}
</style>
<script type="text/javascript">
function chngClss(){
if(document.all){
var cl=document.styleSheets[0].rules[0];
}else{
var cl=document.styleSheets[0].cssRules[0];
}
cl.style.font="4em Courier,monospace";
}
</script>
</head>
<body>
<div class="testClass" onclick="chngClss();">Test Text</div>
</body>
</html>
[change ¦ to unbroken pipes, as usual]
function getSelector(sText)
{
var S = document.styleSheets[0]
var rules = S.rules¦¦S.cssRules // IE ¦¦ others
for(var r=0;r<rules.length;r++)
if(rules[r].selectorText==sText)
return rules[r].style
return null;
}
With this, you put in the selector that you want to target, using the full text (ie including dot, hash whatever), and remembering that it's case sensitive.
It's called getSelector, but it actually returns the associated rule's style object, so you apply the property directly (without reference to '.style'). This can easily be changed, if you want to do more.
getSelector("p").fontSize = "18px"
getSelector(".myclass").backgroundColor = "#008000"
getSelector("#an_id").backgroundColor = "green"
It only looks in the 1st stylesheet. There would be a touch more complication if it did otherwise. It's still more efficient to put the returned object into a local var if you are changing more than one property at a time.
var cellStyle = getSelector("td")
/* perhaps test too*/ if(cellStyle)
{
cellStyle.backgroundColor = "#123456"
cellStyle.color = "#aaaaaa"
}
[quirksmode.org...]
The situation is the same when trying to get the current style properties of an element when not applied inline (again, to be avoided when not just having fun).
In standards browsers, in is more difficult, and many properties can apparently have bugs associated with them in certain browser builds.
IE doesn't follow the standards, but its own standard is very easy to use [.currentStyle], and seems to be followed to a tee.
The fact that IE produces exactly the same string that you put in for a property could have downsides, especially with colours, but it also raises an interesting possiblity. Improper values are not returned for standard CSS properties, but if you use custom properties in your stylesheet, you can get the values out using curentStyle, properly cascaded. This means that you can associate, and group, strings of information to elements via a stylesheet. Rollover image paths, styles etc. perhaps