Reputation: 8352
I have a HTML object element which is retrieved by
document.getElementById()
Is there any way to find out what styles are applied to this element? Not just class name set in CSS attribute. What I need is similar to the style inspect feature of FireBug (FF Addons). Is this possibly done with JavaScript?
Upvotes: 1
Views: 221
Reputation: 4681
You should be able to do this via getComputedStyle()
. You can then use getPropertyValue()
to extract whatever CSS rule you are looking for, or you just iterate over all values:
let element = document.getElementById("test");
let styles = window.getComputedStyle(element);
let bg = styles.getPropertyValue("background-color");
let fg = styles.getPropertyValue("color");
console.log(bg);
console.log(fg);
div {
color: #333;
border-radius: 0.25rem;
}
<div id="test" style="background: #ccc">Hello World</div>
Note, however, these two important quotes from the MDN:
The returned style is a live CSSStyleDeclaration object, which updates automatically when the element's styles are changed.
And:
The returned CSSStyleDeclaration object contains active values for CSS property longhand names. For example, border-bottom-width instead of the border-width and border shorthand property names.
Upvotes: 1