How to Count the Number of HTML Lines When Clicking a JavaScript Button?

Estimated read time 2 min read

Here’s an example of how you could count the number of lines in an HTML element when clicking a JavaScript button:


<div id="textContainer">
  This is line 1.
  This is line 2.
  This is line 3.

<button id="countButton">Count Lines</button>
<p id="output"></p>


const countButton = document.getElementById("countButton");
const textContainer = document.getElementById("textContainer");
const output = document.getElementById("output");

countButton.addEventListener("click", function() {
  const lines = textContainer.innerText.split("\n");
  const lineCount = lines.length;
  output.innerText = "Number of lines: " + lineCount;

In this example, we have a div element with id “textContainer” that contains the text to be counted, a button with id “countButton”, and a p element with id “output” to display the number of lines.

When the button is clicked, the addEventListener method is used to register a click event listener on the button. The function inside the addEventListener method retrieves the text from the “textContainer” element, splits it into an array of lines using the split method with \n as the separator, and then counts the number of lines by getting the length of the array. The result is then displayed in the “output” element.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply