30

This is a very simple question, so I'll keep it really brief:

How can I tell if a particular DOM element's CSS property is inherited?

Reason why I'm asking is because with jQuery's css method it will return the computed style, which inherits the parent object's CSS properties. Is there a way to retrieve the properties set on the object itself?

An example might explain what I'm getting at a bit better:

CSS:

div#container {
  color:#fff;
}

HTML:

<div id="container">
  Something that should be interesting
  <div class="black">
    Some other thing that should be interesting
  </div>
</div>

So, in the instance of div.black, which inherits color, how can I tell if it is inherited?

$('div.black:eq(0)').css('color') will obviously give me #fff, but I want to retrieve the style of the element itself, not its parents.

John
  • 1
  • 13
  • 98
  • 177
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320

7 Answers7

11

To actually determine whether a css style was inherited or set on the element itself, you would have to implement the exact rules that the browsers apply to determine the used value for a particular style on an element.

You would have to implement this spec that specifies how the computed and used values are calculated.

CSS selectors may not always follow a parent-child relationship which could have simplified matters. Consider this CSS.

body {
    color: red;
}

div + div {
    color: red;
}

and the following HTML:

<body>
    <div>first</div>
    <div>second</div>
</body>

Both first and second wil show up in red, however, the first div is red because it inherits it from the parent. The second div is red because the div + div CSS rule applies to it, which is more specific. Looking at the parent, we would see it has the same color, but that's not where the second div is getting it from.

Browsers don't expose any of the internal calculations, except the getComputedStyle interface.

A simple, but flawed solution would be to run through each selector from the stylesheets, and check if a given element satisfies the selector. If yes, then assume that style was applied directly on the element. Say you wanted to go through each style in the first stylesheet,

var myElement = $('..');
var rules = document.styleSheets[0].cssRules;
for(var i = 0; i < rules.length; i++) {
    if (myElement.is(rules[i].selectorText)) {
        console.log('style was directly applied to the element');
    }
}
Anurag
  • 140,337
  • 36
  • 221
  • 257
  • 1
    Thanks for your answer. So what would be a *good* solution then? – Jacob Relkin Feb 16 '11 at 18:49
  • 2
    @Jacob - a good robust solution would have to implement that linked w3 [spec](http://www.w3.org/TR/CSS2/cascade.html), and keep track of style inheritance. Josh's answer works for cases where the css selectors follow a parent-child relationship (see the `div + div` for a counter-example). Looping through the CSS selectors in my example works if that selector was not overridden by a more specific selector, like a `#someId` beats a `div`. – Anurag Feb 17 '11 at 01:03
  • Specificity and inheritance are two different matters - the mere presence of the `div + div` rule is what makes the second div red; the fact that it is more specific than `body` is totally irrelevant, because one applies to a div while the other applies to the page body. – BoltClock May 09 '12 at 14:57
  • 1
    @BoltClock - the fact that the `body` selector is there is important because had the `div + div` selector not been there, then the div's color would have still been red, because of inheritance. In the absence of this specific selector, inheritance wins. When the specific selector is present, it beats inheritance. – Anurag May 09 '12 at 17:59
  • Yes, but that does not have anything to do with selector specificity. – BoltClock May 09 '12 at 18:10
  • Agreed, specificity and inheritance are orthogonal. – Anurag May 09 '12 at 18:12
7

I don't think you can tell if the given style is inherited, I think the best you can do is to set the given CSS property to "inherit", capture its computed value, and compare it to the original value. If they are different, the style is definitely not inherited.

var el = $('div.black:eq(0)');
var prop = el.css("color");
el.css("color", "inherit");
var prop2 = el.css("color");
el.css("color", prop);
if(prop != prop2)
  alert("Color is not inherited.");

Demo on jsFiddle

The point is this: If you set div.black to #fff in the CSS or via inline style, this method will consider that to be inherited. Not ideal, in my opinion, but it may suit your needs. I'm afraid a perfect solution requires traversal of the entire stylesheet.

Josh Stodola
  • 81,538
  • 47
  • 180
  • 227
2

I know this is an old question, however I thought I'd share what I've done with Josh's answer, viz: modified it to remove the css if it was inherited, and turned it into a jQuery plugin. Please feel free to shoot it down, but so far it is working for me :-)

$.fn.isInheritedStyle = function(style) {
    var current = this.css(style);
    this.css(style, 'inherit');
    var inherited = this.css(style);
    if (current == inherited)
        this.css(style, '');
    else
        this.css(style, current);
    return (current == inherited);
}
Dave Nottage
  • 3,411
  • 1
  • 20
  • 57
2

The JS (not jQuery) element.style property returns a CSSStyleDeclaration object thus:

{parentRule: null, 
length: 0, 
cssText: "", 
alignContent: "", 
alignItems: ""…

If the style you are interested in has a value then it's declared (or applied by JS) at the element level, else is inherited.
The information came from https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style

I was struggling with HTML5 Dnd adding display:list-item at the element level (li) and breaking another hide/show filter functionality; I was able to fix it this way.
My specific code was:

// browser bug? it adds display:list-item to the moved elements, this
// loops clear the explicit element-level "display" style
var cols = $('#columnNames li');
for( var icol = 0; icol < cols.length; icol++) {
    var d = cols[icol].style; // the CSSStyleDeclaration 
    d.display = ""; // clear the element-level style
}
Juan Lanus
  • 2,293
  • 23
  • 18
2

http://jsfiddle.net/k7Dw6/

var $black = $('div.black:eq(0)');
alert($('<div>').attr('class', $black.attr('class')).css('line-height') === $black.css('line-height'));

You could create a new element with the same class (and ID I guess) and check if the CSS property is the same or not.

mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • The new element would need to be inserted into the DOM as a sibling in order to inherit the same styles... – Josh Stodola Feb 15 '11 at 06:12
  • @Josh: What!?? That's *exactly* what I *don't* want. The whole point of creating a new element is that it *won't* inherit anything, so we can compare whether the values are coming from inheritance, or from the class. – mpen Feb 15 '11 at 07:26
  • 3
    @Mark - you should not rely on the example given by OP to solve the general problem. Selectors can get extremely [complex](http://www.w3.org/TR/css3-selectors/#selectors) - they can be combined. A style could also come from a class only when it is present in a certain document structure. What if the CSS selector was - `div > div.black`? Then you would have to create two divs, nest one inside the other, and assign the class `"black"` to the inner div for it to get the `line-height` style, then do any comparisons. – Anurag Feb 15 '11 at 17:17
  • @Anurag: That doesn't make sense either, and my solution *is* general. `$black` is just the name of the element he's checking, and `line-height` is the property he's checking against -- easily substitutable. Who cares what the CSS selector is? I don't care *how* the value got inherited, just that it did. If the ... okay. Nevermind, I see what you're saying now. I guess it depends on how you defined "inherit" then..ugh. Setting a value on a parent is just as good as setting it on the child usually... but I'd call that inheritance, but if you want to set it on a nieghbour... – mpen Feb 17 '11 at 03:08
  • And use a weird little + selector and *not* call that inheritance... well... OK then, you have a point. – mpen Feb 17 '11 at 03:09
  • 1
    @Mark - the reason I gave the link to selectors was to show their complexity and the fact that they don't always follow a parent-child relationship. Broadly speaking there can be attribute selectors -`div[data-type="person"] > span.name`, structural selectors - `div:nth-child(odd)`, or selectors that change state depending on user interactions - `div:hover`. This is just a small set of examples to demonstrate why a simple parent-child assumption may not work for all cases. While some of these selectors may be uncommon, the fact that they are there makes the problem more complicated. – Anurag Feb 17 '11 at 17:59
  • @Anurag: I'm well aware of all the different selectors. My logic when I thought up this answer was that if we remove the element from the DOM, you can tell if its CSS properties are coming from the class/ID defined on it, or if they're coming from somewhere else. Either from a parent, or from an attribute selector, or child selector, or whatever. – mpen Feb 19 '11 at 02:18
1

If you're interested in how the style is different from a parent element you could look at the css value which has been given to the parent by saying $('div.black:eq(0)').parent().css('line-height'). In this way you could tell if the child and the parent had the same value. What you can glean from this, however, is limited. It is possible that both the child and the parent have been explicitly assigned the same thing!

If you're interested in the far-more-complex structure of the cascade (e.g. like what you can see in firebug) then I don't have a good answer for you that uses only jQuery. There will be some inefficient hack you can perform depending on the specific information you want (like cloning the object as others suggested, or toggling classes and checking the effect of the toggle), but it makes me upset just thinking about it!

As I think someone noted, vanilla JS does allow you to inspect the properties of specific style items; so maybe a hybrid of jQuery and vanilla JS will get you what you need?

Check out http://developer.apple.com/internet/webcontent/styles.html to see the javascript which gives you access to stylesheet information. AFAIK this isn't going to be an "out of the box for free" type of thing from jQuery (could totally be wrong). That said, it should be possible if you are willing to iterate through the stylesheet information.

Edit: Removed some stuff based on the original question's example code

slifty
  • 13,062
  • 13
  • 71
  • 109
  • 2
    Well, I do care. The entire point is to check if the styles do cascade. – Jacob Relkin Feb 15 '11 at 05:45
  • 1
    Maybe you could give us some insight as to your specific use case? PLEASE note that in your example the 5em isn't inherited, but actually is assigned to the inner div because the style is for ALL div elements. It would be 5 em even if the inner div wasn't wrapped at all. The real issue here is there are a lot of ways a style can cascade. – slifty Feb 15 '11 at 05:48
  • No problem - sorry for sounding confused! I've updated my answer, although I don't have one that uses jQuery; I just know that there are some tricks that JS can let you pull out style information as defined inside of the sheets themselves. – slifty Feb 15 '11 at 06:05
-3

I think, it's nice behavior of jquery. What do you want to get when $('div.black:eq(0)').css('line-height'), false, or undefined? This is so confusing, because real value of line-height (inherited, yes) is 1 em.

MDI
  • 177
  • 10