Link to home
Create AccountLog in
Avatar of NewWebDesigner
NewWebDesigner

asked on

Why is my javascript not working

What is going on here?  Why don't I get an alert when the page loads?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
window.onload = initPage;

function initPage() {
	

document.getElementsByTagName("div") = displayID;
}

function displayID() {
	alert("hey");
}
</script>

</head>

<body>

<div id ="and1" >lkjkjk</div>
</body>
</html>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Gregg
Gregg
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
When you use document.getElementsByTagName("div"), you are essentially creating an  array of div elements. You potentially can have more than one div. In this situation you need to reference the index to retrieve a specific div. The index is a zero based meaning the first instance starts with zero, not one.
And you need to assign the method to an event. No the element itself. If you had 3 divs in you page, you could reference each one with 0,1, 2 in the brackets.

If you only want to reference a specific div, use document.getElementById("and1");
Sorry i misread the question,

document.getElementsByTagName("div")[0] = displayID();

Adding the parentheses will execute the method at page load.