Search code examples
javascriptstylesheet

insertRule does not insert style element


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>


Solution

  • 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>