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);
2
  • is your code in a separate JavaScript section? Commented Jan 9, 2016 at 14:53
  • 1
    Possible duplicate of What does getElementsByClassName return? Commented Jan 9, 2016 at 14:54

4 Answers 4

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Muhammad but what about class, in my case i'm using class, it's not working the same for class
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.

Comments

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);
});

2 Comments

Not desirable? That is what OP Wants.
it give's me an error Cannot read property 'length' of undefined
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

2 Comments

but what about class, in my case i'm using class, it's not working the same for class
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.