Last active
July 4, 2019 07:34
-
-
Save ajaegers/9783820 to your computer and use it in GitHub Desktop.
Apply / trigger dynamically css of pseudo classes with javascript (like in console)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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