cvoigt
cvoigt

Reputation: 587

GetElementsByTagName(tag).length

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.

Upvotes: 2

Views: 2317

Answers (2)

Paul
Paul

Reputation: 141839

Your problem is that this line:

var ul = document.getElementById('listing');

is executing before your ul exists. Either move your whole script somewere below your </ul>, put your code in a window.onload/$(document).ready callback, or simply move that line into your function (which will also make your ul variable be locally scoped to that function):

function countLi(){
    var ul = document.getElementById('listing');
    alert("There are "+ul.getElementsByTagName('li').length+" Li-Elements in this Documnet!");
}

Upvotes: 5

hkutluay
hkutluay

Reputation: 6944

Try like this.Listing element not ready when your code block rendered.

function countLi(){
    var ul = document.getElementById('listing');
    alert("There are "+ul.getElementsByTagName('li').length+" Li-Elements in this Documnet!");
    }

Upvotes: 2

Related Questions