0

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?

roostaamir
  • 1,928
  • 5
  • 24
  • 51

3 Answers3

2

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>
James Thorpe
  • 31,411
  • 5
  • 72
  • 93
1

You can just append a style-element to your document. See this answer: How to create a <style> tag with Javascript

Community
  • 1
  • 1
fredefox
  • 681
  • 3
  • 11
1

Just create a new Style tag and paste your CSS code there:

native javascript:

function addStyle(css) {
    var head = document.head || document.getElementsByTagName('head')[0],
    var style = document.createElement('style');

    style.type = 'text/css';
    if (style.styleSheet){
      style.styleSheet.cssText = css;
    } else {
      style.appendChild(document.createTextNode(css));
    }

    head.appendChild(style);
}

Jquery:

function addStyle(css) {
    $("head").append("<style type='text/css'>"+css+"</style>");
}
Error404
  • 719
  • 9
  • 30