最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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

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

Share Improve this question asked Oct 14, 2010 at 14:40 seedgseedg 21.9k10 gold badges44 silver badges59 bronze badges 1
  • 3 That should work, if you have a single element with the id test in your page. – Oded Commented Oct 14, 2010 at 14:42
Add a comment  | 

3 Answers 3

Reset to default 8

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);
};

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);
发布评论

评论列表(0)

  1. 暂无评论