0

Given css class:

.red {
    color: rgb(255,0,0);
   background-color: rgb(0, 255, 0);
}

I then add a div to the dom via:

$("<div></div>").addClass("red").hide().appendTo("body");

I can get single properties using:

$(".red").css("color");

Which returns rgb(255, 0, 0);

My question is how can I loop through the css class properties and return them all without directly using the property name?

Huangism
  • 16,278
  • 7
  • 48
  • 74
  • Maybe this answer might help: http://stackoverflow.com/questions/1004475/jquery-css-plugin-that-returns-computed-style-of-element-to-pseudo-clone-that-ele – Newtt Oct 01 '14 at 14:08
  • I've actually got that answer open in another tab its not really what I'm after but thanks for the suggestion! :) – Stephen Tierney Oct 01 '14 at 14:13
  • So you want to retrieve the property as it was *set*, what it was *evaluated to*? – David Thomas Oct 01 '14 at 14:20
  • David I want to return both the properties (or key value pair) that are applied to the div: i.e. "color":"rgb(255, 0, 0)" then next loop should return "background-color":"rgb(0, 255, 0)" and so on – Stephen Tierney Oct 01 '14 at 14:26
  • You say without explanation that you don't want to get the computed styles, but that's exactly what you're asking for and it's the only practical solution. – Pointy Oct 01 '14 at 14:28
  • So what you're saying is that it is not possible to get the stylesheet styles only? (i.e. the color and the background-color properties) – Stephen Tierney Oct 01 '14 at 14:30
  • @StephenTierney: You can always iterate all stylesheets (look into their CSSOM) and test whether each selector applies to the selected element. – Bergi Oct 01 '14 at 14:48
  • That's a very helpful suggestion Bergi I will have a look thanks! – Stephen Tierney Oct 01 '14 at 14:57

1 Answers1

0

I've actually found a solution using this very handy jQuery library: https://github.com/f0r4y312/jquery-stylesheet

I can now loop through each stylesheet and the declaration and return:

var key is a loop through the css property names
$.stylesheet("." + key + "").rules()[0].style

Which then returns all the style properties:

0 "color" "rgb(255, 0, 0)"
1 "background-color" "rgb(0, 255, 0)"
etc

Which I'm now serialising into a json array for a unit test!

Thanks for all your very helpful replies!