Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

document.getElementById(loopID)

Status
Not open for further replies.

hunt00

Technical User
Mar 6, 2005
79
US
I am trying to use the ID through the loop, but error:
document.getElementById(firstN)has no properties

count = 5; //5 is set up temporary
for (i=0; i<5; i++) {
firstN = 'firstN'+i;
firstN = 'secondN'+i;
document.getElementById(firstN).innerHTML = txt[2];
document.getElementById(secondN).innerHTML = txt[1];
}
 
did you number your elements 1-5 or 0-4? If 1-5 then your loop would break looking for id 'firstN0'. Also, secondN never gets declared.

=========================================
Don't sweat the petty things and don't pet the sweaty things.
 
count = 20; //20 is set up temporary
for (i=0; i<count; i++) {
firstN = 'firstN'+i;
secondN = 'secondN'+i;
document.getElementById(firstN).innerHTML = txt[2];
document.getElementById(secondN).innerHTML = txt[1];
}

the error shows document.getElementById(firstN)has no properties....which to me means, it couldnt find 'firstN0', 'firstN1', 'firstN2'......although in my html code, those also show up as the IDs when looping through on html page
 
First you should declare your variables just for the sake of good programming but that is not the problem here.
You do not need the variables for firstN and secondN as you can do it right in the getElementById line like so:
Code:
var count = 20; //20 is set up temporary
for (var i=0; i<count; i++) {
  document.getElementById('firstN'+i).innerHTML = txt[2];
  document.getElementById('secondN'+i).innerHTML = txt[1];
}

I suspect what is happening though is that you have this code running on your page but not within a function and that this code is executing BEFORE the HTML on the page actually creates the fields you are trying to alter. Since the fields do not yet exist you get errors trying to manipulate their properties.

Wrap the above code into a function and use an onload event to run it so it does not execute until the page has been rendered and all the elements exist.


It's hard to think outside the box when I'm trapped in a cubicle.
 
Thanks very much! Now works! Your suspect is correct. That is the most basic reason. :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top