Put your script AFTER the actual element, otherwise by the time you run your javascript code, there is no such element in the DOM yet.
<html>
<body>
<input type="button" id="btn1" value="Clickme" onclick="alert('1')" />
<script>
var x = document.getElementById('btn1');
alert(x);
</script>
</body>
</html>
Alternatively, put your script in the DOM ready event to make sure the DOM is fully loaded by the browser before trying to manipulate it:
<html>
<body>
<script>
window.onload = function() {
var x = document.getElementById('btn1');
alert(x);
};
</script>
<input type="button" id="btn1" value="Clickme" onclick="alert('1')" />
</body>
</html>
source
share