Hi I am trying to change the style inside of an external .css file. You can compile this only on a localhost or a online server. Please help. Thank you!
It keep saying "cannot read properties undefined"
and the external style.css only contains
body{}
and it keeps giving me an error. What I am doing it wrong?
this is what I am working at:
function setStyleRule(type, attrs) {
var sheetName = "style";
var sheets = document.styleSheets,
stylesheet = sheets[(sheets.length - 1)];
for (var i in document.styleSheets) {
if (sheets[i].href && sheets[i].href.indexOf(sheetName + ".css") > -1) {
stylesheet = sheets[i];
break;
}
}
var thisCSS = stylesheet;
//console.log(thisCSS);
var ruleSearch = thisCSS.cssRules ? thisCSS.cssRules : thisCSS.rules;
console.log(ruleSearch.length)
for (var i = 0; i < ruleSearch.length; i++) {
console.log(i, ruleSearch[i].selectorText, type)
if (ruleSearch[i].selectorText == type) {
var target = ruleSearch[i];
console.log(target)
break;
}
}
for (var keys in attrs) {
if (attrs.hasOwnProperty(keys)) {
target.style[keys] = attrs[keys];
}
}
}
window.onload = function() {
setStyleRule("body", {
"background-color": "red"
});
}
body {}
I added console.logs that explains you the problem. You set the target inside an if that is never true. So set the target to nothing outside the loop and test if it is even found
Test it here - it cannot be tested at SO due to errors when loading my stylesheet into SO's iFrame (cross origin)
var target;
console.log(ruleSearch.length)
for (var i = 0; i < ruleSearch.length; i++) {
console.log(i, ruleSearch[i].selectorText, type)
if (ruleSearch[i].selectorText == type) {
target = ruleSearch[i];
console.log("found", target)
break;
}
}
if (!target) {
console.log(type, "not found")
return
}
Also I suggest you use addEventListener
window.addEventListener("DOMContentLoaded", function() {
setStyleRule("body", {
"background-color": "red"
});
})