Piotr Mirosz
Piotr Mirosz

Reputation: 866

text length from paragraph using javascript

I would like to count characters from paragraph using JavaScript. example:

HTML:

<p id="text">Example</p>

Javascript

some code

output

7.

I would like to have same effect like jQuery code:

$("#text").text().length;

but i need JavaScript some help?

I've already tried

var x = document.getElementById("text").length;

output: undefined

Upvotes: 0

Views: 4037

Answers (1)

Sanchit Patiyal
Sanchit Patiyal

Reputation: 4920

You need to get innerHTML/innerText of an element before calculating its length like this

var x = document.getElementById("text").innerText.length;
console.log("Length - " + x);
<p id="text">Example</p>

P.S Read here for Difference between innerText and innerHTML

Upvotes: 5

Related Questions