I tried to count the <li>-Elements within an <ul>-Listing. I expected it to work like this:
(The JavaScript):
var ul = document.getElementById('listing');
function countLi(){
alert("There are "+ul.getElementsByTagName('li').length+" Li-Elements in this Documnet!");
}
(The HTML):
<input type="button" onclick="countLi()" value="Count the Li's!"/>
<ul id="listing">
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
It tells me, that “ul is null”. So where is my fault?
Kind regards,
vogti
Edit:
Ah, yeah. I did a Fiddle for you.
Your problem is that this line:
is executing before your
ulexists. Either move your whole script somewere below your</ul>, put your code in awindow.onload/$(document).readycallback, or simply move that line into your function (which will also make yourulvariable be locally scoped to that function):