3

Is there any way to know if an element height or width was set (not auto) in javascript/css ? elm.style.height will only return a value if the height is defined inside the element attribute list : <div style='height:200px' .... ></div>, otherwise it will always return an empty string even if you define the height inside a style tag or a css file : .myElmCss{height:200px}.

On the other hand, using window.getComputedStyle() or elm.currentStyle will always return a value even if no height was defined neither inside the element attribute list nor in a css file/style tag.

Thanks.

Yaco
  • 31
  • 1
  • Sorry I don't quite understand the answer, could you explain more clearly? – Jose Faeti Jun 22 '11 at 16:28
  • Well, suppose these 2 elements : 1-
    inner content ...
    and 2-
    inner content ...
    , and the css class : .myElm{height:200px;}. In both cases you can't tell if the element height is auto (like in the 2nd case) or not (1st case). How would you do ?
    – Yaco Jun 22 '11 at 18:52

1 Answers1

1

Check this post How do you read CSS rule values with JavaScript?

To do what you're looking for it appears to be a matter of iterating over the stylesheets to find declared properties. You would probably also cross reference with inline styles like you mentioned in your question.

from @InsDel's post:

function getStyle(className) {
    var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules
    for(var x=0;x<classes.length;x++) {
        if(classes[x].selectorText==className) {
                (classes[x].cssText) ? alert(classes[x].cssText) : alert(classes[x].style.cssText);
        }
    }
}
Community
  • 1
  • 1
MikeM
  • 27,227
  • 4
  • 64
  • 80
  • Thanks @InsDel. I already thought about something like this, I personally was hoping a function or something less heavy than iterating through all the document style list. I think I'm going to stick to that. thanks again. – Yaco Jun 22 '11 at 17:14
  • Hi @InsDel, will this work if the element style is defined by its id instead of its class, like : #myElm{height:200ppx}. – Yaco Jun 22 '11 at 18:51
  • sorry @InsDel, I didn't vote for your answer I'm not registered. – Yaco Jun 22 '11 at 18:58
  • Forget the question about the id, I just read the post you mentioned, it works even for a class defined by id. thanks. – Yaco Jun 22 '11 at 19:52
  • What about Jquery? `$('element').width();` o.O – Tomas Ramirez Sarduy Oct 25 '12 at 06:40
  • @TomSarduy the jQuery function returns the computed value, i.e. it will never return "auto" or "100%" - it will always return pixels. – allicarn Jan 03 '14 at 20:10