Middle
How to get the width of a DOM element and track its changes? Can you attach a resize event to a DOM element using addEventListener?
sobes.tech AI
Answer from AI
To get the width of a DOM element, you can use the offsetWidth property or getBoundingClientRect().width:
const element = document.getElementById('myElement');
const width = element.offsetWidth;
// or
const widthRect = element.getBoundingClientRect().width;
To track changes in the element's width, you cannot directly attach a resize event via addEventListener, as the resize event is only available on the window object.
Instead, use ResizeObserver — a modern API that allows monitoring changes in element sizes:
const resizeObserver = new ResizeObserver(entries => {
for (let entry of entries) {
console.log('New width:', entry.contentRect.width);
}
});
resizeObserver.observe(element);
Thus, ResizeObserver is the correct way to monitor changes in the size of a DOM element.