0

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);
Viktor
  • 722
  • 1
  • 8
  • 25
  • is your code in a separate JavaScript section? – Peter Smith Jan 09 '16 at 14:53
  • 1
    Possible duplicate of [What does getElementsByClassName return?](http://stackoverflow.com/questions/10693845/what-does-getelementsbyclassname-return) – JJJ Jan 09 '16 at 14:54

4 Answers4

1

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.

Peter Smith
  • 5,528
  • 8
  • 51
  • 77
1

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);
});
void
  • 36,090
  • 8
  • 62
  • 107
1

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
Sachin
  • 1,208
  • 1
  • 10
  • 20
  • but what about class, in my case i'm using class, it's not working the same for class – Viktor Jan 09 '16 at 15:29
  • getElementByClass() returns an array of elements. You can refer to @void's answer. It works for class. It makes sense if you have more than one such element. – Sachin Jan 09 '16 at 15:32
1

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>
Wasiq Muhammad
  • 3,080
  • 3
  • 16
  • 29
  • Muhammad but what about class, in my case i'm using class, it's not working the same for class – Viktor Jan 09 '16 at 15:29