Reputation: 5118
Can anyone explain to me why the following code doesn't work within a function but outside of a function it works perfectly?
function calculate_document_forms_length(){
document.forms.length;
}
Running it from the console returns "undefined", but when I just run document.forms.length from the console itself returns the number of forms on the page. I've tried to understand why this isn't working but I'm unable to find a reason for it. It happens in firefox, and also chrome. I see no reason why that shouldn't work.
Edit to clarify a few things.
It's ran from the console after the page is done loading. And the following returns the proper value.
document.forms.length;
Thus I don't know why it's acting this way.
OK here's the exact source of the test HTML page.
<html>
<head>
<title>test page 01</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<body>
<form>
<input type="text" name="test1" />
</form>
<form>
<input type="text" name="tes2" />
</form>
</body>
</html>
As you can see no frames, nothing but plain HTML and forms within the tag.
Upvotes: 0
Views: 2675
Reputation: 11
The problem is that your code document.forms.length;
runs before the whole page is rendered.
To fix this:
Upvotes: 0
Reputation: 1
This doesn't answer the why but if you return it, it works:
function aa(){
return document.forms.length;
}
Upvotes: 0
Reputation: 18773
The function you have there doesn't return anything (i.e. when you run it, it "returns" undefined
). Try this instead:
function() {
return document.forms.length;
}
Also, if you run just that in the console, you'll still get undefined
, because you're still not calling the function. You're just creating it, but it's still not being executed.
If you want to run it in the console, you can write
(function() {
return document.forms.length;
}());
Lastly, if you just write document.forms.length
in the console, the console will show you the value, because length
is a variable. So that's why that seemed to work.
Upvotes: 2