简体   繁体   中英

Can't access DOM element

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?

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 ie "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)

becomes

document.getElementById('test')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM