Categories
JavaScript Answers

How to determine if an HTML element’s content overflows with JavaScript?

Spread the love

To determine if an HTML element’s content overflows with JavaScript, we check if the parent width is smaller than the element’s width.

For instance, we write

const checkOverflow = (elem) => {
  const elemWidth = elem.getBoundingClientRect().width;
  const parentWidth = elem.parentElement.getBoundingClientRect().width;

  return elemWidth > parentWidth;
};

to get the elem element’s width with elem.getBoundingClientRect().width;.

We get its parent’s width with elem.parentElement.getBoundingClientRect().width;.

And then if elem‘s width is bigger than parentWidth, then elem overflows its parent.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *