Viktor
Viktor

Reputation: 722

How to make character count with Javascript

How to correctly make a character count with JS. My code seems is incorrect, what i'm doign wrong?

<p class="text">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>

    var str = document.getElementsByClassName('text');
    var res = str.innerHTML = str.value.length;
    console.log(res);

Upvotes: 0

Views: 82

Answers (4)

Wasiq Muhammad
Wasiq Muhammad

Reputation: 3118

This can work for you

var x = document.getElementById("text").innerHTML
var str = x.length;
alert("length is:" +str);
console.log(str);
<p id="text">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>

Upvotes: 1

Sachin
Sachin

Reputation: 1218

I guess you want to get the length of the content of an element. For that you should be using id selector, not class selector, there can be many elements with the same class but not with the same id. So you should give it some id like: <p id='some_id' class='text'>
Now you can get it through:

document.getElementById("some_id").innerHTML.length

To avoid any leading or trailing spaces, and to get exact length of text, you can try this:

document.getElementById("some_id").innerHTML.trim().length

Upvotes: 1

void
void

Reputation: 36703

getElementsByClassName() returns an array-like collection of elements. Iterate over it and fetch the value:

var str = document.getElementsByClassName('text');
[].forEach.call(str, function(el){
   var res = el.value.length;
   el.innerHTML = res;
   console.log(res);
});

Upvotes: 1

Peter Smith
Peter Smith

Reputation: 5550

If you look at this definition of the function it returns an array. So you either want the length of the array str.length or to iterate through the array.

Upvotes: 1

Related Questions