Jump to content

Can you use a variable with getElementById?


SmokingMan
 Share

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...