Search code examples
jquerycssgetcomputedstylecomputed-style

How to get in Javascript / jQuery only CSS override properties


I am trying to obtain the list of CSS properties of an element that are overridden, example:

.div{
  position:absolute;
  top:10px;
}

When we use this code:

jQuery('.div').css('bottom');

I obtain:

bottom:-10px;

If I use get computed or jquery.css I will get the same result, but in fact I want to obtain:

empty or null 

because I didn't specify / overridden.

Values expected in this example: top: 10px bottom: auto or null or nothing

https://codepen.io/anon/pen/dvvdVv

Again, I only wanted the properties that were overridden.

===================== EDIT ======================

My objective is only to get the value top,bottom from the following element:

<div id='box' class='giveItSomeTop' style="top:10px"></div>

and the css for the element, notice that I have only specified top:

.giveItSomeTop{
   top:10px;
}

Now I want to get the top value and the bottom value. If I do:

$('#box').css('top');

The result is: 10px but when I do:

$('#box').css('bottom');

I get 700px when I should get empty, nothing, null or ''


Solution

  • Unfortunately you are not using the jQuery css() method how it is intended.

    https://api.jquery.com/css/

    Get the value of a computed style property for the first element in the set of matched elements or set one or more CSS properties for every matched element.

    This means, it does not care what the CSS file has applied to this element, it will only look for what you have asked it to look for on the element.

    What you will need to do it write a CSS file parser, and then query from that.. But it's another tool/library you will need to implement.

    And there are answers for such a tool on StackOverflow : Parsing CSS in JavaScript / jQuery

    And / Or : Convert CSS text to JavaScript object

    From here you will be given a null|undefined for object properties which do not exist.