2

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!

3
  • care to explain what error you're getting? That's fine as far as FireBug is concerned... Commented May 20, 2009 at 10:55
  • 1
    Just as a comment, I'm going to suggest one of the major javascript libraries for this sort of thing, because we can't drill that in around here enough. (jQuery/prototype/YUI/Dojo/Moo) - Yes, it's worth the overhead. Commented May 20, 2009 at 10:57
  • add this script block end of the page Commented May 20, 2009 at 11:24

5 Answers 5

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

+1 good point, I was thinking about it and then you've posted your answer :)
2

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

Comments

1

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

3 Comments

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..
Well ARE there any selects on the page? If so - what browser are you testing this on?
yes there are selects and im testing IE and Opera, but i only need this script for IE any way...
1

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.

Comments

0

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)

1 Comment

All have id's as its ASP.net any its a asp.net control :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.