Donatas Cereska
Donatas Cereska

Reputation: 545

How to get element width/height with margin, padding, border in Native JavaScript (no jQuery)

Looking for reliable method to calculate the element's width/height + margin - padding + border using native JS only and be xbrowser (IE8+)

Upvotes: 45

Views: 76148

Answers (2)

YSLdev
YSLdev

Reputation: 173

A less tedious method is to use the element.getBoundingClientRect as @Mehran Hatami mentioned.

Here's the code you need:

let elem = document.querySelector("<element>");
let rect = elem.getBoundingClientRect();
if(rect){
  const { width, height } = rect;
  console.log( width, height )
}

Upvotes: 0

reaxis
reaxis

Reputation: 1431

If you're only dealing with pixel values for the margin, padding and border properties, you can do the following:

// we're assuming a reference to your element in a variable called 'element'
var style = element.currentStyle || window.getComputedStyle(element),
    width = element.offsetWidth, // or use style.width
    margin = parseFloat(style.marginLeft) + parseFloat(style.marginRight),
    padding = parseFloat(style.paddingLeft) + parseFloat(style.paddingRight),
    border = parseFloat(style.borderLeftWidth) + parseFloat(style.borderRightWidth);

alert(width + margin - padding + border);

If you're dealing with other kinds of values (like ems, points or values like auto), I would like to refer you to this answer.

Upvotes: 68

Related Questions