I have a for loop which has an if statement nested inside of it, but the loop is ignoring the statement and continuing to run. Any ideas why this could be? Many thanks.
JavaScript:
var sheet = document.styleSheets[0];
var cssVal = '';
function changeColor() {
for (i = 0; i < sheet.cssRules.length; i++) {
cssVal = sheet.cssRules[i];
console.log(cssVal); // Successfully outputs #box to the console.
if (cssVal == "#box") { // Does nothing, continues iterating.
console.log("If has run.");
cssVal.style.backgroundColor="blue";
break;
}
}
}
changeColor();
CSS:
@charset "utf-8";
#box {
width:20px;
height:20px;
}
#car {
width:20px;
height:20px;
}
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Boxes</title>
<link href="Boxes.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="box"></div>
<div id="car"></div>
<script type="text/javascript" src="Boxes.js"></script>
</body>
</html>
Obviously it isn't going inside the if
, that's because cssVal
is not a string
, it's a CSSStyleRule
object. You should do this instead:
cssVal = sheet.cssRules[i];
Then in your if
:
if (cssVal.selectorText == '#box')
And then, to change the color:
cssVal.style.backgroundColor = "blue";
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments