views:

285

answers:

5

Well im new to javascript but why does this not work, all i want to do is to get a list of all selects on the page.

var elements = document.getElementsByTagName("select");
alert("there are " + elements.length + " select's");
for (i = 0; i < elements.length; i++)
{
    alert(elements[i].getAttribute('Id'));
}

Edit: the error is that it does not find any selects at all, elements.length is allways zero!

+1  A: 

I guess the part of getting id attribute doesn't work for you. Probably it's because you typed there "Id" instead of "id".

Artem Barger
it says "there are 0 select's" all the time, and changing to id does not help as it dosent find any that invalid code didnt do any harm yet..
Petoj
Well ARE there any selects on the page?If so - what browser are you testing this on?
Ramuns Usovs
yes there are selects and im testing IE and Opera, but i only need this script for IE any way...
Petoj
Did you tried it for other tags?
Artem Barger
+2  A: 

Try using .id instead of of getAttribute('Id').

Hank Gay
A: 

Well, as far as I can see is that perhaps the selects on your page don't have Id's (the alerts in the loop show null)

Ramuns Usovs
All have id's as its ASP.net any its a asp.net control :)
Petoj
+3  A: 

You'r saying that elements.length is always returning 0 for you, this could be because:

  • You are running the JS code in the beginning of your page, thus the DOM is not fully available yet
duckyflip
+1 good point, I was thinking about it and then you've posted your answer :)
Artem Barger
A: 

The usual cause for getElementsByTagName returning zero results in a document with matching elements is that it is being run before the elements appear in the document (usually in the section and not inside a function that is called onload or onDomReady).

Move the element to just before the (END of body!) tag, or use an event handler that fires after the HTML has all been processed.

David Dorward