I'm trying to add a new style element into the HTML. I am currently using the code snippets from this blog post http://davidwalsh.name/add-rules-stylesheets
When it runs in codepen http://codepen.io/angelathewebdev/pen/vEjNvj?editors=101, I can't see the styles. There is a style element injected, but the style rules are not injected. There is no error thrown either.
When I obtain the stylesheet object, I don't see the insertRule or addRule property.
function addCSSRule(sheet, selector, rules, index) {
if("insertRule" in sheet) {
sheet.insertRule(selector + "{" + rules + "}", index);
} else if("addRule" in sheet) {
sheet.addRule(selector, rules, index);
}
}
var style = document.createElement('style');
// WebKit hack :(
style.appendChild(document.createTextNode(''));
// Add the <style> element to the page
document.head.appendChild(style);
// Stylesheet Rules
addCSSRule(style.sheet, '.red', "background: red;", 1);
<div class="red" style="width: 50px; height: 50px;"></div>
It's because of index which you are passing is out of bound.
For insertRule you need not pass index.
if("insertRule" in sheet) {
sheet.insertRule(selector + "{" + rules + "}");
Else pass 0
addCSSRule(style.sheet, '.red', "background: red;", 0);
DEMO
function addCSSRule(sheet, selector, rules, index) {
if("insertRule" in sheet) {
sheet.insertRule(selector + "{" + rules + "}", index);
} else if("addRule" in sheet) {
sheet.addRule(selector, rules, index);
}
}
var style = document.createElement('style');
// WebKit hack :(
style.appendChild(document.createTextNode(''));
// Add the <style> element to the page
document.head.appendChild(style);
// Stylesheet Rules
addCSSRule(style.sheet, '.red', "background: red;", 0);
<div class="red" style="width: 50px; height: 50px;"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With