Reputation:
I have a problem with length property returning "undefined" after that I've written my code.
My task is getting length of the text. I've tried out to do it, but it doesn't work.
Let's look at my code and find an error.
<h1 id="t">tt</h1>
<input type="submit" value="q" onclick="hide()">
<script>
function hide() {
var qq = document.getElementById('t').length;
alert(qq);
}
Friends, I will be grateful, if you will say where is the error. :) Thanks in advance.
Having solved the problem, I think you are good.
Upvotes: 4
Views: 4722
Reputation: 6302
The document.getElementById('t') just returns the DOM, not a string. The string is inside on the innerHTML property.
var qq = document.getElementById('t');
alert(qq.innerHTML.length);
Upvotes: 1
Reputation: 4173
Use
var qq = document.getElementById('t').innerHTML.length;
instead
as getElementById
returns a single element .length
is undefined. .length
is only available on arrays.
You can access the content of the <h2>
element by gettings its innerHTML
property
Upvotes: 7
Reputation: 4022
document.getElementById
does not return text. It returns the DOM element itself.
If you want the content of the HTML emlement, use innerHTML
or innerText
var qq = document.getElementById('t').innerHTML.length;
Upvotes: 1
Reputation: 1586
getElementById
returns the element. You need the text inside the element. element.innerHTML
will do the trick in this case.
Upvotes: 5