Line clamp a DOM element in vanilla JavaScript.
- Truncates in pure JavaScript; does not rely on
-webkit-line-clamp
- Works even if the given element contains nested DOM nodes
- Supports appending a custom string instead of an ellipsis (
…
) - 477 bytes gzipped
HTML:
<div class="line-clamp">
Lorem ipsum dolor sit amet, <strong>consectetur adipiscing</strong> elit.
</div>
CSS:
.line-clamp {
width: 100px;
line-height: 20px;
}
JavaScript:
const element = document.querySelector('.line-clamp')
lineClamp(element, 3)
Boom:
<div class="line-clamp" style="overflow: hidden; overflow-wrap: break-word; word-wrap: break-word;">
Lorem ipsum dolor sit amet, <strong>consectetur…</strong>
</div>
- The element is assumed to have a pixel line-height, obtained via
window.getComputedStyle
.
const lineClamp = require('line-clamp')
options
is an optional object literal.
- Set
options.ellipsis
to change the string to be appended to the truncated text. Defaults to…
.
See Usage.
Install via yarn:
$ yarn add line-clamp
Or npm:
$ npm install --save line-clamp