Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the actual inherited CSS of an element using JavaScript?

Tags:

javascript

css

Using JavaScript, how can I get the actual value for a CSS property which is inherited?

For example, consider the following HTML:

<p><span style="font-size:24pt;">Test #1</span></p>​
<p style="font-size:24pt;">Test <span style="font-weight:bold;">#2</span></p>​

Using the jQuery code $('p span').css('fontSize') will yield 32px not 24pt because it uses getComputedStyle which returns the used value, not the actual inherited value. But sometimes the style will be directly on the element I am targeting, sometimes it will be inherited.

Here is a test case. How can I get the actual inherited CSS of an element using JavaScript?

like image 658
Josh Avatar asked Apr 02 '12 20:04

Josh


People also ask

How do you retrieve a CSS property value of an element?

The attr() CSS function is used to retrieve the value of an attribute of the selected element and use it in the stylesheet. It can also be used on pseudo-elements, in which case the value of the attribute on the pseudo-element's originating element is returned.

How do CSS styles for a particular element get inherited?

What is CSS inheritance? CSS rulesets cascade down the CSS hierarchy from parent selectors to their children selectors. These CSS rulesets are inherited from their parent selectors. The child element will naturally inherit a CSS property with its value from the parent element if the CSS property is not specified.

How do I find the CSS of an element?

The CSS of an element can be obtained using the getComputedStyle element function in JavaScript. It returns a JavaScript object containing CSS properties and their values. This object is indexed and iterable over the property names. The getPropertyValue(property) is used to get the value of a property.

Can I use inherit CSS?

The inherit keyword specifies that a property should inherit its value from its parent element. The inherit keyword can be used for any CSS property, and on any HTML element.


1 Answers

The answer by @mikerobi would satisfy your test case, but to be more specific the only CSS properties exposed by the browsers are from getComputedStyle, so if it's wrong there that's about as good as it gets. See this answer from another question for more detail.

like image 87
Alex Vidal Avatar answered Oct 16 '22 00:10

Alex Vidal