tags:

views:

86

answers:

2

Let's say i have some html code like this

<html>
<body>
    <div class="container">
    <div class="markup-container">
        <div class="title">This is a title with some markup</div>
        <div class="body">This is the body with some markup and it's longer ^^</div>
    </div>
    </div>
</body>
</html>

and my css looks like this

.container{display:none;}
.markup-container{color:#404040;}
.title{text:decoration:underline;}
.body{color:#000;}

How do i get my javascript to read all the CSS used in the class container (including children).

I want it to display it, the same way as it has been written in css and put it in a variabel like:

var css = "<style type="text/css">.container{display:none;}.markup-container{color:#404040;}.title{text:decoration:underline;}.body{color:#000;}"

How would i do this?

+1  A: 

When you use jQuery's css method, you are storing the CSS in a way that allows it to be easily applied to another element. It would be particularly long-winded, usually impractical and unusual to get the CSS for multiple selectors and store it in one variable.

You can retrieve a single CSS property of a single selector with jquery like so:

var css = $('.container').css('display');

The simplest technique of storing the CSS as a string would require you to have the CSS in the same place as the HTML (i.e. not in a seperate CSS file). You could store the css as a string by adding an ID to it like so:

<style id="my_css" type="text/css">
    .container{display:none;}
    .markup-container{color:#404040;}
    .title{text:decoration:underline;}
    .body{color:#000;}
</style>

and then store that text in your javascript with

var css = $('#my_css').text();

I've got an example of this in action up here - http://jsbin.com/umire3

Dr. Frankenstein
I just want to clarify things. `.css( propertyName )` , `propertyName` is required.
Reigel
thanks @Reigel +1, ammended answer
Dr. Frankenstein
Just to be sure.It isn't possible to load the css of an external css file?And it's not possible to load all the properties at once? :)
NicoJuicy
As @Babiker has pointed out, you can use `document.styleSheets` to grab code from external stylesheets - see http://www.quirksmode.org/dom/tests/stylesheets.html for more on this.
Dr. Frankenstein
+1  A: 

With plain JavaScript, you could do the following:

var styleSheet = document.styleSheets[0]; //first stylesheet.
var css='<style type="text/css">';
for(i=0; i<styleSheet.cssRules.length; i++)
 {
    css += styleSheet.cssRules[i].cssText;
 }
css = css + "</style>";
Babiker