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')