Karan Parikh
Karan Parikh

Reputation: 321

Is adding multiple rules to css using insertRule() possible?

Hi this is the HTML code

<html>
<head>
 <link rel="stylesheet" type="text/css" href="Theme.css"> 
</head>
<body>
<div>
    <textarea id="ta" onpaste="functionItalic(event)" class="foostyle2"></textarea>
</div>
<div>
    <span style="font-weight: bolder; font-size: 20px;">
        <span id="1">Karan's</span>
     </span>
    <span style="font-weight: bolder; font-size: 24px; font-style: italic;">test</span>
</div>
<script>
function functionItalic(pasteEvent)
{
var textareacont = (pasteEvent.originalEvent || pasteEvent).clipboardData.getData("text/html");
console.log(textareacont);
var styleSheetList = document.styleSheets;
document.getElementById("1").className = "foostyle";
var stringCSS = ".foostyle{font-family: Times-Roman;font-size:10pt;color:rgb(0,0,0);font-style:normal;}";
styleSheetList[0].insertRule(stringCSS, styleSheetList[0].cssRules.length);

}
</script>
</body>
</html>

When I run this file everything works fine and style gets added.

But as soon I as change the value of stringCSS to

var stringCSS = ".foostyle{font-family: Times-Roman;font-size:10pt;color:rgb(0,0,0);font-style:normal;} .foostyle2{background: green;}";

The browser provides an error

SyntaxError: An invalid or illegal string was specified
styleSheetList[0].insertRule(stingCSS, styleSheetList[0].cssRules.length);

What am I missing is adding multiple classes/rule through insertRule not possible or I have done some mistake? please help.

Upvotes: 3

Views: 2402

Answers (1)

adeneo
adeneo

Reputation: 318312

The specification states that

If more than one rule is given in the rule parameter, then aborts with SyntaxError

So what is a rule, the specification also says that a rule is

... a DOMString containing the rule to be inserted, ...where rule specifies selector and declaration, or at-identifier and rule content.

So it's a string with a "selector and a declaration" of styles, in other words a rule is

.selector {declaration : of_styles}

or with the "at-identifier and rule content"

@font-face { font-family: 'font'; src: local('font'), url(/font.ttf); }

You're passing it

.foostyle{font-family: Times-Roman;font-size:10pt;color:rgb(0,0,0);font-style:normal;} 
.foostyle2{background: green;}

which is two rules, and it aborts with a syntax error, as expected.

To solve it, you have to call insertRule() twice, once for each rule

Upvotes: 7

Related Questions