Sometimes, we want to check whether the text-overflow
ellipsis is rendered in the element.
In this article, we’ll look at how to check for the text-overflow
ellipsis in an HTML element.
Check if offsetWidth is Less than scrollWidth
The offsetWidth
property of an element tells us the width of the element rendered on the screen.
scrollWidth
tells us the width of the element including the truncated parts.
Therefore, we can see if a piece of text is truncated with the CSS text-overflow
property by checking whether offsetWidth
is less than scrollWidth
.
For instance, if we have the following HTML:
<div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam in neque laoreet, venenatis quam id, tristique ipsum. Sed augue ipsum, pharetra in ipsum eget, varius placerat odio. Pellentesque a luctus metus, commodo placerat elit. Nullam efficitur augue in magna consectetur finibus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Cras porttitor lectus pretium, placerat nulla eget, hendrerit magna. Nunc in sem dui. Sed sollicitudin sem a massa malesuada cursus. Mauris feugiat enim sit amet efficitur lobortis.
</div>
And CSS:
div {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
Then we can do the check by writing:
const isEllipsisActive = (e) => {
return (e.offsetWidth < e.scrollWidth);
}
const div = document.querySelector('div')
console.log(isEllipsisActive(div))
We do the comparison between offsetWidth
and scrollWidth
as we specified in the isEllipsisActive
function.
Then we get the div with querySelector
and pass it into the isEllipsisActive
.
So the console log should log true
since we truncated the text with the CSS.
Conclusion
We can check if a piece of text is truncated with the CSS text-overflow
property by checking whether the offsetWidth
of the element is less than its scrollWidth
.
One reply on “How to Check for text-overflow Ellipsis in an HTML Element?”
This is exactly what I needed to know, thank you!