tags:

views:

308

answers:

2

I've written this sample code to print the length of x. But for some reason, I am not getting anything! Help!

<html>
<head>
<script type = "text/javascript">
function myF()
{
   var x = [1,2,3,4];
   var y = document.getElementById("thing");
   y.innerHtml = x.length;
}
</script>
</head>

<body onload = "myF();" >

<div id = "thing" >
PRINT TEST
</div>

</body>
</html>
A: 

In the onload event, the dom-tree is not fully loaded yet. So getElementById wil return nothing.

You'll have to delay the execution of your function

Ikke
getElementById is not returning null.
lYriCAlsSH
The DOM *is* loaded once onload is fired.
Andy Hume
`onload` only gets called after the DOM is fully loaded (and all images are loaded), so DOM-readiness is not the problem in this case.
Jeff M
+7  A: 

The property name is innerHTML rather than innerHtml.

Andy Hume
Thank you!... dunno why i did that...
lYriCAlsSH
Why does the Firefox error console not return an error when this is done?
Unkwntech
@Unkwntech: Why should it? DOM nodes are objects, so you're free to add any property you like - even ones named 'innerHtml'...
Christoph
@Unkwntech: Because That's JavaScript's syntax to assign new properties to instantiated objects. So what happened in that line was the object stored in 'y' had a new property name 'innerHtml' attached and assigned the length of array x.
xk0der
I thought so, it was asked for the sake of the question asker.
Unkwntech
I'd look at using jQuery(el).html() instead. It'll be future proof.
Rob Stevenson-Leggett