Use getBoundingClientRect() for accurate dimensions
const element = document.querySelector('.box');
const rect = element.getBoundingClientRect();
console.log(rect.width, rect.height);const box = document.querySelector('.box');
// Get dimensions with position
const rect = box.getBoundingClientRect();
console.log({
width: rect.width,
height: rect.height,
top: rect.top,
left: rect.left
});
// Get scroll dimensions
console.log({
scrollWidth: box.scrollWidth,
scrollHeight: box.scrollHeight,
clientWidth: box.clientWidth,
clientHeight: box.clientHeight
});
// Window dimensions
console.log({
windowWidth: window.innerWidth,
windowHeight: window.innerHeight,
documentHeight: document.documentElement.scrollHeight
});
// Check if element is visible
const isVisible = rect.width > 0 && rect.height > 0;function getOffset(element) {
const rect = element.getBoundingClientRect();
return {
top: rect.top + window.pageYOffset,
left: rect.left + window.pageXOffset
};
}const isMobile = window.innerWidth < 768;
const isTablet = window.innerWidth >= 768 && window.innerWidth < 1024;Avoid offsetWidth/offsetHeight for precise measurements
// DON'T DO THIS - less accurate, no decimal values
const width = element.offsetWidth;✓ Works in all modern browsers (IE9+)