I’m trying to get a DOM element from JavaScript. Even though the ID is correct, getElementId can’t seem to find it; I get a
TypeError: Cannot read property ‘innerHTML’ of null
in Chrome, or a
TypeError: x is null
in Firefox using only the simple code below. Why is this?
<!DOCTYPE html>
<html>
<head>
<script>
var x = document.getElementById("myHeader");
alert(x.innerHTML);
</script>
</head>
<body>
<h1 id="myHeader">Click me!</h1>
</body>
</html>
Or leave it in the
<head>but wrap it in a function and call it when<body>is loaded