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

javascript - Can't access DOM element - Stack Overflow

programmeradmin0浏览0评论

I wrote a web application with a body onload event. I know this isn't optimal so I want to use DOMContentLoaded to trigger my init event.

I have a strange problem, I can't access my DOM element and I don't know why :/.

HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
    <script type="text/javascript" src="main.js"></script>
</head>
<body>
    <div id="test">Hello World</div>
</body>
</html>

JS:

// add event listener
document.addEventListener('DOMContentLoaded', init, false);

function init () {
    // pop up
    alert(document.getElementById(test).innerHTML);
}

Does somebody see the problem?

I wrote a web application with a body onload event. I know this isn't optimal so I want to use DOMContentLoaded to trigger my init event.

I have a strange problem, I can't access my DOM element and I don't know why :/.

HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
    <script type="text/javascript" src="main.js"></script>
</head>
<body>
    <div id="test">Hello World</div>
</body>
</html>

JS:

// add event listener
document.addEventListener('DOMContentLoaded', init, false);

function init () {
    // pop up
    alert(document.getElementById(test).innerHTML);
}

Does somebody see the problem?

Share Improve this question asked Mar 3, 2013 at 14:19 Philippe MaesPhilippe Maes 51010 silver badges28 bronze badges 1
  • How about the generic window.onload=init or is it just your test that needs to be quoted? – mplungjan Commented Mar 3, 2013 at 14:22
Add a ment  | 

3 Answers 3

Reset to default 3

You are passing the undefined variable test to the getElementById() function, instead of the string value 'test'.

So

document.getElementById(test); // Incorrect - as an undefined varible

Should in fact be

document.getElementById('test') // Correct - as a string value

Or

var element_id = 'test';
document.getElementById(element_id) // Correct - as a defined variable

Add double quotes around test i.e. "test"

document.addEventListener('DOMContentLoaded', init, false);

function init () {
    // pop up
    alert(document.getElementById("test").innerHTML);
}

If your init function is executed, then you might add quote arroud your id :

document.getElementById(test)

bees

document.getElementById('test')
发布评论

评论列表(0)

  1. 暂无评论