Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get a dynamic id with getElementById in Javascript?

Tags:

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

like image 764
seedg Avatar asked Oct 14 '10 14:10

seedg


2 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: http://jsfiddle.net/kARDy/

window.onload = function() {

    var myVar;
    myVar = 'test';

    var element = document.getElementById(myVar);

    alert(element.innerHTML);
};
like image 135
user113716 Avatar answered Sep 18 '22 20:09

user113716


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';
}
like image 24
meder omuraliev Avatar answered Sep 21 '22 20:09

meder omuraliev