How do I retrieve an HTML element's actual width and height?
To retrieve an HTML element’s actual rendered width and height, you have multiple approaches in vanilla JavaScript and jQuery. Here are the most common methods:
1. offsetWidth
and offsetHeight
const element = document.getElementById('myElement'); const width = element.offsetWidth; const height = element.offsetHeight; console.log(width, height);
- Includes padding, the element’s borders, and vertical scrollbars (if any), but not margins.
2. clientWidth
and clientHeight
const width = element.clientWidth; const height = element.clientHeight;
- Includes padding but excludes borders, margins, and scrollbars.
3. getBoundingClientRect()
const rect = element.getBoundingClientRect(); const width = rect.width; const height = rect.height;
- Returns a
DOMRect
object containing the element’s size and its position relative to the viewport. - Especially handy when you need both position (e.g.,
left
/top
) and size (width
/height
).
4. jQuery Methods
If you’re using jQuery:
const $el = $('#myElement'); const width = $el.width(); // Content width (no padding, borders, or margin) const height = $el.height(); const outerW = $el.outerWidth(); // Includes padding + border const outerH = $el.outerHeight(); console.log(width, height, outerW, outerH);
outerWidth(true)
andouterHeight(true)
can also include margins.
Best Practices
- Decide if you need borders, padding, or margins in the measurement.
offsetWidth
/offsetHeight
is a quick go-to for an element’s “box” size.- If you need precise location on the screen, or if the element might be transformed (e.g., scaled), use
getBoundingClientRect()
.
Enhance Your JavaScript Skills
To deepen your knowledge of DOM manipulation and core JavaScript concepts, consider these courses from DesignGurus.io:
You can also explore the DesignGurus.io YouTube channel for additional tutorials and discussions on front-end development, coding interview tips, and software design.
CONTRIBUTOR
TechGrind