Element.prototype.getBoundingClientRect
Returns a DOMRect object providing information about the size of an element and its position relative to the viewport
Syntax
element.getBoundingClientRect()Return Value
A DOMRect with top, right, bottom, left, width, height, x, y properties
Examples
const el = document.querySelector('.box')!
const rect = el.getBoundingClientRect()
console.log(`Position: ${rect.top}, ${rect.left}`)function isInViewport(el: HTMLElement): boolean {
const rect = el.getBoundingClientRect()
return rect.top >= 0 && rect.bottom <= window.innerHeight
}function getCenter(el: HTMLElement) {
const rect = el.getBoundingClientRect()
return {
x: rect.left + rect.width / 2,
y: rect.top + rect.height / 2
}
}Understanding Element.prototype.getBoundingClientRect
The Element.prototype.getBoundingClientRect method in JavaScript returns a DOMRect object providing information about the size of an element and its position relative to the viewport. It belongs to the Element object and is one of the most widely used methods for working with element values in modern JavaScript and TypeScript applications.
The method signature is element.getBoundingClientRect(). When called, it returns a domrect with top, right, bottom, left, width, height, x, y properties. Understanding when and how to use getBoundingClientRect() helps you write more expressive, readable code.
Common use cases for Element.prototype.getBoundingClientRect include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like dom-scrollintoview, dom-offsetwidth, dom-clientheight, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for Element.prototype.getBoundingClientRect is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
Element.prototype.scrollIntoViewScrolls the element's ancestor containers so the element is visible to the user
HTMLElement.prototype.offsetWidthReturns the layout width of an element as an integer, including padding, border, and vertical scrollbar
HTMLElement.prototype.clientHeightReturns the inner height of an element in pixels, including padding but excluding borders, margins, and horizontal scrollbars
More Element Methods
Other methods in the Element object
Related Tools
More Element Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.