getElementByID questions

Hi,

I have the following code which only works when I use a <p> tag rather than <div> tag.

Is there a reason why a <div> doesn’t work?

Thanks


<script>
function displayDate()
{
document.getElementByID("test") .innerHTML=Date();
}
</script>

<button type="button" onclick="displayDate()">test</button>
<p id="test">
show date
</p>

It shouldn’t make a difference. You do have two errors in your code, though: ID instead of Id, and a gap before .innerHTML. Try this instead:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>

<button type="button" onclick="displayDate()">test</button> 
<div id="test"> 
show date 
</div>  

<script> 
function displayDate() { 
	document.getElementById("test").innerHTML=Date();
} 
</script> 
</body>
</html>

or this

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>

<button id="button" type="button">test</button> 
<div id="test"> 
show date 
</div>  

<script> 
var button = document.getElementById("button");
var test = document.getElementById("test");
button.onclick = function displayDate() {
    test.innerHTML = Date();
}
</script> 
</body>
</html>

Hi,

The code will work with both a <div> and a <p> and any other element that you can attach an id to.

I think the problem is that you have a typo in your code.

This:

document.getElementByID("test") .innerHTML=Date(); 

should be this:

document.getElementById("test").innerHTML=Date();

Hope that helps.

Edit: Oops. Ralph was quicker.