Sunday, April 8, 2012

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

2 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