How to show just the first line of text of a div and expand on click with JavaScript?

Sometimes, we want to show just the first line of text of a div and expand on click with JavaScript.

In this article, we’ll look at how to show just the first line of text of a div and expand on click with JavaScript.

How to show just the first line of text of a div and expand on click with JavaScript?

To show just the first line of text of a div and expand on click with JavaScript, we can set the height of the div.

For instance, we write:

<div>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas nibh tortor, consectetur in felis nec, elementum condimentum felis. Aliquam et condimentum dui. Quisque luctus purus mauris, non fringilla lectus mollis sit amet. Vivamus vitae lectus ut ex tristique tincidunt eget ac urna.
</div>

to add a div with text.

Then we write:

div {
  border: 1px solid red;
  height: 1em;
  padding: 2px;
  overflow: hidden
}

to set the height of the div to show a single line.

Next, we write:

const div = document.querySelector('div')
div.onclick = (e) => {
  e.target.style.height = 'auto'
}

to select the div with querySelector.

And then we set div.onclick to a function that sets the height of the div to 'auto'.

Conclusion

To show just the first line of text of a div and expand on click with JavaScript, we can set the height of the div.