views:

156

answers:

3

does anyone know how can i get all styles applied to an id using jquery (so i can reuse it later in another tag)? something like css:

div#myid{
width:100px;
height:100px;}

so i can later do something like:

for (var parts in $('#myid').css())
alert ('all parts of the style' + parts);
+2  A: 

$('#myid').attr('class') returns a string of the classes.

You should be able to figure it out from here.

var classes = $('#myid').attr('class').split(' ');
for(var c in classes)
{
    alert(classes[c]);
}
ctrlShiftBryan
One small change would be alert(c); //Classes[c] will throw an error
Raja
Yea not sure 'c' was coming back as an int for some reason...
ctrlShiftBryan
A: 

It is not jquery but works well:

var style = window.getComputedStyle(document.getElementById('myid'), null);
    alert(style.color);

You can replace document.getElementById('myid') by $('#myid').get(0) if you really want to use jquery here.

This works either for a style given by CSS or directly applied on the element with the style attribute.

Mic
A: 

not sure.. i had tried attr('class') before and it returned empty. trying now again produces the same result (nearly). i suppose attr('class') in jquery isnt exactly the same as styles defined via id. try running this, let me know if you get different results please:

<html>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"&gt;&lt;/script&gt;
<script type="text/javascript">
  $(document).ready(function (){
    alert($('#myid').attr('class')); // returns 'empty'
    var classes = $('#myid').attr('class').split(' ');
    for(var c in classes){
      alert(c); // returns 0
    }
   });
</script>

<style>
#myid {
width:100px;
height:100px;
background:red;
}
</style>

<body>
<div id="myid"></div>
</body>

</html>
joe
is window.getComputedStyle cross browser compliant by any chance? :)
joe