roostaamir roostaamir - 4 months ago 5
HTML Question

Is there a javascript library that reads a style string and adds the appropriate styles to given elements?

I am looking for a library/code that reads styles for the elements from a string and then applies the styles to the elements in that string. For example consider this code:

jsLibrary.setStyle("body{width:90%}div{background:red}.blue{color:bule}");


I want this library to read the string passed to it as parameter and then set the styles for
body
,
div
, and
.blue
.

does such a thing exist?

Answer

You don't need a library or any complicated parsing code to do this - you can simply insert a <style> element with the relevant text - the browser will parse and use it as normal.

var s = document.createElement('style');
s.innerText = "body{width:90%}div{background:red}.blue{color:blue}";
document.body.appendChild(s)
<div>abc</div>
<div class="blue">xyz</div>

Comments