简体   繁体   中英

How to check what styles are applied to an element?

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?

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.

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