Sometimes, we want to check with JavaScript if div has overflowing elements.
In this article, we’ll look at how to check with JavaScript if div has overflowing elements.
How to check with JavaScript if div has overflowing elements?
To check with JavaScript if div has overflowing elements, we can compare the element’s height with its scroll height.
For instance, we write
<div class="overflow-hidden" style="height: 20px">
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the
1500s, when an unknown printer took a galley of type and scrambled it to
make a type specimen book. It has survived not only five centuries, but also
the leap into electronic typesetting, remaining essentially unchanged. It
was popularised in the 1960s with the release of Letraset sheets containing
Lorem Ipsum passages, and more recently with desktop publishing software
like Aldus PageMaker including versions of Lorem Ipsum.
</div>
</div>
to add nested divs.
Then we write
const element = document.querySelector(".overflow-hidden");
if (
element.offsetHeight < element.scrollHeight ||
element.offsetWidth < element.scrollWidth
) {
// ...
} else {
// ...
}
to select the outer div with querySelector
.
And we get its height with offsetHeight
.
We get its content’s full height with scrollHeight
.
We do the same with the width.
If offsetHeight
is less than scrollHeight
then the height overflows.
If offsetWidth
is less than scrollWidth
then the width overflows.
Conclusion
To check with JavaScript if div has overflowing elements, we can compare the element’s height with its scroll height.