Peter
Peter

Reputation: 38485

JavaScript, loop all selects?

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!

Upvotes: 2

Views: 784

Answers (5)

Quentin
Quentin

Reputation: 943593

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.

Upvotes: 1

duckyflip
duckyflip

Reputation: 16499

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

Upvotes: 3

Ramuns Usovs
Ramuns Usovs

Reputation: 1454

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)

Upvotes: 0

Hank Gay
Hank Gay

Reputation: 71949

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

Upvotes: 2

Artem Barger
Artem Barger

Reputation: 41232

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

Upvotes: 1

Related Questions