47

It's possible to get the element outerWidth using the dom?

Ej:

var width = document.getElementById('myDiv').outerWidth; 
Cœur
  • 37,241
  • 25
  • 195
  • 267
Martin Borthiry
  • 5,256
  • 10
  • 42
  • 59

2 Answers2

71

No, but you can get offsetWidth, which is probably what you want.

From http://www.quirksmode.org/dom/w3c_cssom.html

offsetWidth and offsetHeight

The width & height of the entire element, including borders and padding (excluding margins).

clientWidth and clientHeight

The width & height of the element including padding (excluding borders and margins)

See this fiddle for an example.

var elm = document.querySelector('div');

document.body.innerHTML += `
  clientWidth: ${elm.clientWidth} px
  <br>
  scrollWidth: ${elm.scrollWidth} px
  <br>
  offsetWidth: ${elm.offsetWidth} px`
  
  
div{
  width      : 200px;
  padding    : 10px;
  border     : 10px solid gold;
  
  margin     : 10px;
  background : lightgreen;
}
<div></div>

If you use jQuery you have more options: width, innerWidth and outerWidth properties. http://api.jquery.com/category/manipulation/style-properties/

vsync
  • 118,978
  • 58
  • 307
  • 400
Sean
  • 15,561
  • 4
  • 37
  • 37
  • 23
    It should be noted, that they aren't *exactly* the same. jQuery will give you the width of the element even if it isn't in the document, or if it is hidden; whereas `element.outerWidth` and `element.clientWidth` will return `0` if the element is hidden, and `undefined` if it is not in the document. – xyhhx Feb 08 '13 at 21:51
  • 2
    offsetWidth is not crossbrowser – Lautaro Cozzani Feb 27 '15 at 18:03
  • 1
    seems like you should use `Element.getBoundingClientRect()` as it is available in browsers other than Chrome (unlike `offsetWidth` and `offsetHeight`). it returns an object with `width` and `height` properties. – sleeparrow Sep 07 '17 at 20:15
6

Sean provided the perfect solution for outerWidth().

Just to add to that, if you're looking for a substitution for any or all of the jQuery dimension getters related to width, see my solution below.

Note: this also provides the correct dimensions even with * { box-sizing: border-box }

function getWidth(el, type) {
  if (type === 'inner') // .innerWidth()
    return el.clientWidth;
  else if (type === 'outer') // .outerWidth()
    return el.offsetWidth;
  let s = window.getComputedStyle(el, null);
  if (type === 'width') // .width()
    return el.clientWidth - parseInt(s.getPropertyValue('padding-left')) - parseInt(s.getPropertyValue('padding-right'));
  else if (type === 'full') // .outerWidth(includeMargins = true)
    return el.offsetWidth + parseInt(s.getPropertyValue('margin-left')) + parseInt(s.getPropertyValue('margin-right'));
  return null;
}
Dylan Maxey
  • 976
  • 10
  • 9