admin管理员组文章数量:1420639
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
3 Answers
Reset to default 3You 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')
本文标签: javascriptCan39t access DOM elementStack Overflow
版权声明:本文标题:javascript - Can't access DOM element - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745292352a2651873.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论