I have created several shapes with CSS, each shape is contained in an element with an id, for example id=”square”. What I want is the following: If I click on the shape, I would like to display its CSS rules in a textarea.
Here’s my HTML:
<ul>
<li><div id="square" class="box"> parallelogram </div></li>
<li><div id="parallelogram" class="box"> parallelogram </div></li>
<li><div id="parallelogram2" class="box"> parallelogram2 </div></li>
</ul>
<textarea name="show" id="show" cols="30" rows="10"></textarea>
And my CSS:
#square {
width: 100px;
height: 100px;
background: blue;
}
#parallelogram {
width:100px;
height:70px;
background:blue;
-webkit-transform:skew(20deg);
-moz-transform:skew(20deg);
-o-transform:skew(20deg);
transform:skew(20deg);
}
#parallelogram2 {
width:100px;
height:70px;
background:blue;
-webkit-transform:skew(-20deg);
-moz-transform:skew(-20deg);
-o-transform:skew(-20deg);
transform:skew(-20deg);
}
And the jQuery code I currently have:
$(".box").click(function () {
var id = $(this).parents().attr('id');
var cssrules=document.styleSheets[0].rules["id"].style.cssText;
$("#show").html("cssrules");
});
Also see this jsFiddle. Here’s another one with all my shapes.
The whitespace issues are actually preventing this from working at all – there is a difference between $(“#show”) and $(“#show “), so you should really be more careful with this. I fixed the markup:
To get your inline style sheet, you should iterate over
document.styleSheetsand grab the one that has anhrefattribute with valuenull– the other ones are external style sheets. Since all your elements are referenced by id and the corresponding CSS rules start with # we can get the rule corresponding to a shape by testing whether theselectorTextattribute of a rule starts with “#”:You can access the style sheets only by index, they’re held in an array. Finally, you have to set the value of the
textarea, not itshtml.Here is a jsfiddle illustrating it.