How Do You Get a Dynamic Id with getElementById in Javascript?

How Do You Get a Dynamic Id with getElementById in Javascript?

I need to get a dynamic value in the document.getElementById in Javascript.

However, when I put a variable it does not work, like so:

var = myVar;
myVar = 'test';

document.getElementById(myVar);

How can I implement this?

Many thanks

1

3 Answers

Your syntax is wrong.

This:

var = myVar;

should be:

var myVar;

So you'd have:

var myVar;
myVar = 'test';

document.getElementById(myVar);

Then you can place the code in an onload to make sure the element is available.

Example:

window.onload = function() {

    var myVar;
    myVar = 'test';

    var element = document.getElementById(myVar);

    alert(element.innerHTML);
};

It will work properly if you do it after the element has rendered, either by adding it in a callback on window.load, DOM ready, or put the script after the element in the HTML.

window.onload = function() {
    var el = 'bla'; document.getElementById(el).style.display='none';
}

Were you supposed to have that equals? It should be:

var myVar = 'test';
document.getElementById(myVar);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi
Author

Maya Lin-Takahashi

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.