Can anyone tell me why when I use the following code, clicking on “Click Here” doesn’t cause an alert? Is there any way to do this without adding an onClick attribute to the div tag?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html>
<head>
<script type="text/javascript">
var clicker = document.getElementById("test");
clicker.onclick = test;
function test() {
alert('Test');
}
</script>
</head>
<body>
<div id="test">Click Here</div>
</body>
</html>
Because the element doesn’t exist when you try to select it.