Skip to main content

How can I tell if a particular CSS property is inherited with jQuery?



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.





EDIT : To clarify, my question is how can I detect if a given CSS property was inherited? That's it.





Thanks



Source: Tips4all

Comments

  1. 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.

    ReplyDelete
  2. 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.

    ReplyDelete

Post a Comment

Popular posts from this blog

Slow Android emulator

I have a 2.67 GHz Celeron processor, 1.21 GB of RAM on a x86 Windows XP Professional machine. My understanding is that the Android emulator should start fairly quickly on such a machine, but for me it does not. I have followed all instructions in setting up the IDE, SDKs, JDKs and such and have had some success in staring the emulator quickly but is very particulary. How can I, if possible, fix this problem?