Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ajaegers/9783820 to your computer and use it in GitHub Desktop.
Save ajaegers/9783820 to your computer and use it in GitHub Desktop.
Apply / trigger dynamically css of pseudo classes with javascript (like in console)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style type="text/css">
div {
display: block;
width: 200px;
height: 200px;
background: red;
}
div:hover {
background: green;
}
</style>
</head>
<body>
<h3>Apply dynamically css of pseudo classes with javascript (like in console)</h3>
<p>Example with :hover<p/>
<div></div>
<button onclick="javascript:applyHoverStyle()">Apply :hover style (should become green)</button>
</body>
</html>
// Find all css properties for the :hover you want
var applyHoverStyle = function() {
var div = document.getElementsByTagName("div")[0];
var i,j, sel = /div:hover/, aProperties = [];
for(i = 0; i < document.styleSheets.length; ++i){
// console.log(document.styleSheets[i]);
if(document.styleSheets[i]. cssRules !== null) {
for(j = 0; j < document.styleSheets[i].cssRules.length; ++j){
if(sel.test(document.styleSheets[i].cssRules[j].selectorText)){
aProperties.push(document.styleSheets[i].cssRules[j].style.cssText);
// console.log(document.styleSheets[i].cssRules[j].selectorText, document.styleSheets[i].cssRules[j].style.cssText);
}
}
}
}
//console.log(aProperties);
div.style.cssText = aProperties.join(' ');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment