Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Suppose I have the following.

HTML:

<div id="foo"></div>

CSS:

#foo{
   width: 150px;
}

JS:

document.getElementById("foo").style.width //Equals to "" instead of 150px
$("#foo").css("width") //equals to the expected "150px"

or this JSFiddle. Why can we access the width of the element using jQuery but not using vanilla JS? Is it because external CSS rules are not part of the DOM?

share|improve this question
3  
jQuery uses document.defaultView.getComputedStyle() (or the alternatives, when that’s not available). You can use that for properties that don’t have… properties (like in the case of offset(Width|Height|Left|Top)). – minitech 1 hour ago
jQuery is vanilla JS w/ some pizzaz. jQuery is pure JavaScript that used to sometimes use Flash to get around some AJAX stuff. Regardless, if you can do it in jQuery, you can do it w/ vanilla JS, you'll just have to manually type it out. – vol7ron 43 mins ago

2 Answers

up vote 1 down vote accepted

Use getComputedStyle. See this updated fiddle:

computedWidth = window.getComputedStyle(document.getElementById("foo"), null).
                getPropertyValue("width");

elem.style will just give you back inline styles associated with the element, i.e. the contents of the style="" attribute.

share|improve this answer

Try offsetWidth. When you try to access style.width, it will give you just the width assigned to the element's style property. But in your case it is assigned the width via css rule.

document.getElementById("foo").offsetWidth;

Fiddle

Edit: clientWidth would probably be more appropriate as it gives you the inner width of the element, where as offsetWidth considers borders, margins as well.

share|improve this answer
1  
offsetWidth will include borders and margins and hence is not equivalent to the CSS width. clientWidth would be more appropriate, but still does not necessarily reflect the CSS width, always (scrollbars). – nmaier 52 mins ago
@nmaier Yeah i forgot about clientWidth, just got mixed up in my mind about both. Thanks Updated. – PSL 47 mins ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.