简体   繁体   中英

Get all CSS styles of an element with JavaScript

Is there a way to select all CSS rules of an element with JavaScript? I'm not looking for a specific solution, just as long as all CSS rules of a given element are read.

So, I have the following HTML

<div class='styledDiv' style='height:100px;width:100px;'></div>

and then in a separate CSS file:

.styledDiv
{
  background-color: #ccc;
  border: solid 5px blue;
}

I'd like the final result to include all inline and separate file CSS rules. It doesn't matter in what format the final result is, be it a string or an array, whatever.

Let me also mention, I looked at some code that reads CSS rules from a separate CSS file. I think there could be a better solution. Also, FireFox and Chrome allow to loop through .style property the same way as looping through an array. However, FF spits out -*tl-source rules for right and left border/margin/padding and doesn't show the actual CSS values. Solution involving jQuery is also fine.

For FireFox, you can use this: https://developer.mozilla.org/en/DOM:window.getComputedStyle

For IE, you can use this: http://msdn.microsoft.com/en-us/library/ms535231(VS.85).aspx

Be aware! You are treading on dark waters here.

These results return the browser's interpretation of CSS. For example, when getting colors, IE would return the HEX color codes while Firefox returns rbg code . And for font sizes IE would return the actual inherited font size while Firefox will return pt based.

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