简体   繁体   中英

How do I return all CSS properties applied to an element by an external stylesheet class (not get computed styles!)?

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?

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM