<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:hover ", we will call it by a
variable name "selector" and the new rules "newRules" then :
var rgs=new RegExp('\\s*'+selector+"\\s*","g")
var css=document.styleSheets;
for(var k=0;k< css.length;k++){
var rules=document.styleSheets[k].cssRules;
for(var i=0;i<rules.length;i++){
if(rgs.test(rules[i].selectorText)) {
rules[i].style.cssText=newRules;
}
}
}
with, for example :
selector="a.myClass:hover";
newRules="padding:0 15px 0 1em; background:#fcefab;";
or, u might want to change only one property for example :
property="background";
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(cssTexts[j])) cssTexts[j]=property+':'+value;
}
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;background:#666;}';
suppose, worst case, we don't have *any* <style ... /in the document
head then :
var head=document.getElementsByTagName('head')[0];
var style=document.createElement('style');
style.type='text/css';
head.appendChild(style);
var aRule='h1, h3 {color:red;background:#666;}';
document.styleSheets[0].insertRule(aRule,0);
otherwise, simplest case, their is allready some styles nodes in your
document, then :
var stylesLen=document.getElementsByTagName('style').l ength;
var
rulesLen=document.getElementsByTagName('style')[stylesLen-1].cssRules.le
ngth;
var aRule='h1, h3 {color:red;background:#666;}';
document.styleSheets[stylesLen-1].insertRule(aRule,rulesLen);