I'm trying to write some automated tests and for some elements the css selector ":hover/:focus" is present , Obviously i can't simulate hover state with pure javascript . So after a bit of searching i've came across this question: How do I simulate a mouseover in pure JavaScript that activates the CSS ":hover"?
And one of the answers gives this snippet :
simulateCssEvent = function(type){
var id = 'simulatedStyle';
var generateEvent = function(selector){
var style = "";
for (var i in document.styleSheets) {
var rules = document.styleSheets[i].cssRules;
for (var r in rules) {
if(rules[r].cssText && rules[r].selectorText){
if(rules[r].selectorText.indexOf(selector) > -1){
var regex = new RegExp(selector,"g")
var text = rules[r].cssText.replace(regex,"");
style += text+"\n";
}
}
}
}
$("head").append("<style id="+id+">"+style+"</style>");
};
var stopEvent = function(){
$("#"+id).remove();
};
switch(type) {
case "hover":
return generateEvent(":hover");
case "stop":
return stopEvent();
}
}
I've actually tried it and its works reasonably ok until i've encountered selectors like:
testdiv > :hover
testdiv > :hover > #testdiv2
after removing ":hover" with the above code the selector will be invalid.
any bulletproof approach for this?