Jump to content

Can you use a variable with getElementById?


SmokingMan

Recommended Posts

When you use "document.getElementById("name")", 'name' is the name you have given a particular id so you can reference it. Can you use a variable in it's place where the id you want to reference may change depending on what the user is doing? This variable would hold the id of the element you want to reference.

Link to comment
Share on other sites

When you use "document.getElementById("name")", 'name' is the name you have given a particular id so you can reference it. Can you use a variable in it's place where the id you want to reference may change depending on what the user is doing? This variable would hold the id of the element you want to reference.
If I understand correctly, you can. Check it out:
var name = "idname";document.getElementById(name);

That will get the element that has the id idname. All you have to do is write the variable inside without the quotes.

Link to comment
Share on other sites

Yes. Try it before asking next time.
Awww take it easy on the guy. I remember back when I had no idea about that. Then I learned you could do stuff like:
var x = 4;document.getElementById("item" + x);

To get something out of the element "item4". Very helpful if you're using JavaScript for something with multiple items of the same type of data and you need to handle each separately.

Link to comment
Share on other sites

Thanks for your help, I guess. I had tried it, but I didn't do it correctly which is why I asked the question. I'll try not to be as stupid in the future.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...