We can use jQuery to get the length of text in a paragraph using the JavaScript String length property. To do this we will get the text from a paragraph in the form of a string using the jQuery val() method. We will then use the length property to get the text length.

var text = $(".p1").val();
var textLength = text.length;

Let’s see a quick example of this below:

Let’s say we have the following HTML:

This is a paragraph with some text.

If we wanted to get the text length of the paragraph in div, #div1, then we would use the following jQuery code:

var text = $("#div1 p").val();
var textLength = text.length;

In the example above, the length of the text would be 35.

If you are using WordPress, don’t forget to change the $ to jQuery as below:

var text = jQuery("#div1 p").val();
var textLength = text.length;

Let’s do an interactive example on jQuery text length below.

Using jQuery to Get Text Length of User Input

Below we will have a simple textarea input. We will let the user enter in or write any amount of text that they want.

Here is our simple HTML:

Type or paste any text you want below:

Get Text Length

Once the user has entered in or written their text, we will simply use the jQuery val() method to get the user input.

Once we have the user text, we can use the length property to get the length of the user text.

Finally, we will use the jQuery text() method to update the text of our #results div.

Here is the JavaScript and jQuery code:

  var userText = $("#userText").val();
  var textLength = userText.length;

The final code and output for this example of using jQuery to get text length is below:

Code Output:

Type or paste any text you want below:

Get Text Length

Full Code:

Type or paste any text you want below:

Get Text Length

Hopefully this article has been useful to help you understand how to use jQuery to get text length.

Categorized in:


Last Update: March 14, 2024