I am looking into web creation and have started making a site just to see how the coding of
websites work and how the files link to each other. So, what I am trying to do is when the page
loads it prompts "What is your name?" with a default value of "John". Then, when the user
hits 'okay' it displays 'Hello John!' or whatever the name is. However, the variable is
not being added to the <p> text. Here are the three files (.htm, .css, .js):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<title>JavaScript Test One</title>
<link rel="stylesheet" type="text/css" href="one.css" />
<script type="text/javascript" src="index.js"></script>

<h1>JavaScript Test Site One</h1>

<table class="pos_fixed">
	<td><a href="#index">Home</a></td>
	<td><a href="#one">One</a></td>
	<td><a href="#two">Two</a></td>
	<td><a href="#three">Three</a></td>
	<td><a href="#four">Four</a></td>
	<td><a href="#five">Five</a></td>

<p style="text-align:center; font-size:30px;" id="helloText">Hello!</p>

<table class="center"> <!-- Spacer -->

<hr />
<p> © WildCat Programming, Inc. </p>

body { background-color:#0099FF; text-align:center;}

h1 { text-align:center; }

a { text-decoration:none; }
a:link { color:#000000; }
a:visited { color:#000000; }
a:hover { color:#FFFFFF; }
a:active { color:#B0B0B0; }

table.pos_fixed { position:fixed; border-style:outset; border-width:5px; width:100px; background-color:#C0C0C0; }

table.center, td.center { margin-left:auto; margin-right:auto; width:50%; height:1500px; }
var name = prompt("What is your name?","John")
if (name!=null && name!="") {
	document.getItemById("helloText").innerHTML='Hello ' + name + '!';
} else {

document.write(name) shows that 'John' is, in fact, saved in the var 'name', but for
some reason it is not being displayed in the paragraph text. I tried deleting all of the
style code from the 'helloText' paragraph, but that still did not display the variable.

So, what (I'm sure) simple thing am I missing/messing up?

Thanks in advance,

- WolfShield

6 Years
Discussion Span
Last Post by WolfShield


The main thing is that the javascript runs as the page loads before the browser has had a chance to convert the HTML into DOM elements and then rendered them. You need to cast the code inside an "onload handler", which runs after the page has loaded.

Another thing is that document.getItemById should be replaced with document.getElementById (twice).

window.onload = function() {
	var name = prompt("What is your name?","John");
	if (name) {
		document.getElementById("helloText").innerHTML='Hello ' + name + '!';
	} else {

I haven't test this but think it should work.


This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.