<mf*****@gmail. comwrote:
I need to access to the hover style of an element with javascript. How
can i do this?
u can bothe add a css rule of modify an existing one.
suppose the declared css is :
a.myClass:hover {<the directives}
in that case u want to modify an existing style.
first u'll have to loop over all the styles nodes, using DOM, in order
to find the selector text "a.myClass:hove r ", we will call it by a
variable name "selector" and the new rules "newRules" then :
var rgs=new RegExp('\\s*'+s elector+"\\s*", "g")
var css=document.st yleSheets;
for(var k=0;k< css.length;k++) {
var rules=document. styleSheets[k].cssRules;
for(var i=0;i<rules.len gth;i++){
if(rgs.test(rul es[i].selectorText)) {
rules[i].style.cssText= newRules;
}
}
}
with, for example :
selector="a.myC lass:hover";
newRules="paddi ng:0 15px 0 1em; background:#fce fab;";
or, u might want to change only one property for example :
property="backg round";
value="blue";
in that case i'll have to split the cssText of the rule corresonding to
the selector like :
var cssTexts=rules[i].style.cssText. split(';');
then loop over the properties to change the "background :
for(var j=0;j<cssTexts. length;j++){
if(rgp.test(css Texts[j])) cssTexts[j]=property+':'+v alue;
}
using another Regexp :
var rgp=new RegExp('^\\s*'+ property+"\\s*: ","g")
then restore the whole cssText by :
rules[i].style.cssText= cssTexts.join(' ;');
that's all if u want to change a property for a given selector.
It is much more easier to *add* a new rule if the rule corresponding to
the selector doesn't exists :
saying we have :
var aRule='h1, h3 {color:red;back ground:#666;}';
suppose, worst case, we don't have *any* <style ... /in the document
head then :
var head=document.g etElementsByTag Name('head')[0];
var style=document. createElement(' style');
style.type='tex t/css';
head.appendChil d(style);
var aRule='h1, h3 {color:red;back ground:#666;}';
document.styleS heets[0].insertRule(aRu le,0);
otherwise, simplest case, their is allready some styles nodes in your
document, then :
var stylesLen=docum ent.getElements ByTagName('styl e').length;
var
rulesLen=docume nt.getElementsB yTagName('style ')[stylesLen-1].cssRules.le
ngth;
var aRule='h1, h3 {color:red;back ground:#666;}';
document.styleS heets[stylesLen-1].insertRule(aRu le,rulesLen);