0

How can I grab entire css from <style id="myId" type="text/css"> to push it into a JSON file?

I am adding dynamically css to <style>, so in my html the style is empty.

Tried with $('#myId').text(), $('#myId').html() with no luck.

I need for this type of output:

function addRule(selector, rules) {
      var stylesheet = document.getElementById('myId');
      if (stylesheet) {
        stylesheet = stylesheet.sheet;
        if (stylesheet.addRule) {
          for (var i = 0; i < selector.length; ++i) {
            stylesheet.addRule(selector[i], rules);
          }
        } else if (stylesheet.insertRule) {
          stylesheet.insertRule(selector.join(',') + ' { ' + rules + ' }', stylesheet.cssRules.length);
        }
      }
}
function pushToJson(){
  item {}
  dataCSS = []
  item ["myCSS"] = '?????'; 
  // here I need the css 
  // eg: "h1 {margin:0;} .title {padding:10px 0;}"
  dataCSS.push(item);
}
addRule(['.title, h2'], 'color:red;');

Any help?

8
  • .text() seems to work just fine for me. Commented Feb 21, 2017 at 10:50
  • Try with document.getElementById('myId').innerHTML Commented Feb 21, 2017 at 10:51
  • wasn't sure until now, that if you add dynamic css into style, you can't grab it with .html(), or I am wrong? Commented Feb 21, 2017 at 10:56
  • Exactly how are you "adding dynamically" css to <style>? Commented Feb 21, 2017 at 10:56
  • 1
    Use the equivalent get property stylesheet.cssRules: developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet Commented Feb 21, 2017 at 11:27

5 Answers 5

1

The equivalent of stylesheet.addRule and stylesheet.insertRule is

stylesheet.cssRules

Here's an example using .cssRules that ignores all the inherited and "actual" css that's applied and reads only the rules in your style tag

See https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet for more info.

function addRule(selector, rules) {
  var stylesheet = document.getElementById('myId');
  if (stylesheet) {
    stylesheet = stylesheet.sheet;
    if (stylesheet.addRule) {
      for (var i = 0; i < selector.length; ++i) {
        stylesheet.addRule(selector[i], rules);
      }
    } else if (stylesheet.insertRule) {
      stylesheet.insertRule(selector.join(',') + ' { ' + rules + ' }', stylesheet.cssRules.length);
    }
  }
}

addRule(['.title, h2'], 'color:red;');
addRule(['body h2'], 'font-weight:normal;');

function pushToJson() {
  var stylesheet = document.getElementById('myId');
  if (stylesheet) {
    stylesheet = stylesheet.sheet;
    for(var i = 0; i<stylesheet.cssRules.length;++i) {
        // Do the JSON magic here
        console.dir(
            stylesheet.cssRules[i].selectorText 
            + " : " 
            + stylesheet.cssRules[i].style.cssText)
    }
  }
}

pushToJson();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style id="myId" type="text/css">
  body {
    background-color: lightblue;
  }
</style>
<h2>Title</h2>

Sign up to request clarification or add additional context in comments.

Comments

1

Following code grabs the entire code from the specified style tag. You can then store it inside a new variable or do whatever you want with it.

var newJSON = {};

function addRule(selector, rules) {
  var stylesheet = document.getElementById('myId');
  if (stylesheet) {
    stylesheet = stylesheet.sheet;
    if (stylesheet.addRule) {
      for (var i = 0; i < selector.length; ++i) {
        stylesheet.addRule(selector[i], rules);
      }
    } else if (stylesheet.insertRule) {
      stylesheet.insertRule(selector.join(',') + ' { ' + rules + ' }', stylesheet.cssRules.length);
    }
  }
  pushToJson();
}

function pushToJson() {
  newJSON = $('#myId').html();
  console.log(newJSON);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style id="myId" type="text/css">
  body {
    background-color: lightblue;
  }
</style>

9 Comments

I forgot to mention that, I am adding css dynamically into <style>
@Adrian What do you mean by dynamically? You are importing another css stylesheet or using an asynchronous call?
Updated my question, wasn't sure that adding later css into my style, can be a problem when I want to grab it :(
addRule() function is executed as first function, right? It fills up the stylesheet with css properties and then you want to export it into JSON?
yes, I run multiple addRule() functions and at the end I run JSON save
|
0

You should try this:

$('#myId').css()

Comments

0
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>

  </title>
  <link rel="stylesheet" href="">
  <style>
    #myname{
      color: red;
    }
  </style>
</head>    


//This Line will yield you the style innerHTML

console.log(document.head.innerHTML);

Comments

0

Use code like this:

var element = document.getElementById('myId'),
    style = window.getComputedStyle(element);
jsonStyle = JSON.stringify(style);

5 Comments

With this I am getting a lot of css, don't know from where. Sample: {"0":"animation-delay","1":"animation-direction","2":"animation-duratio..
You take all of style of this element include inherited
if you need to take just itself try use this code: var style = document.getElementById('myId').style, jsonStyle = JSON.stringify(style);
again is getting strange css {\"alignContent\":\"\",\"alignItems\":\"\",\"alignSelf\":\"\",\"alignmentBasel..
did this maybe it will help fiddle

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.