Creating a website on the fly using getElementById?
I am trying to create a web site on-the-fly using JavaScript, but can't get my getElementById function to work properly. I've poked around a good bit and found examples and try w/o success to make them work(the majority of them did not use an external .js file). Below is the code my JavaScript and HTML:
HTML:
<!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>
<title>Final Project</title>
<script type="text/javascript">
</script>
</head>
<body>
<script type="text/javascript" src="finalProj.js">
</script>
<form name = "myForm">
<h1 id="m开发者_开发问答yHeader"></h1>
JavaScript:
var firstName = ("RicK");
var courseName = ("WEB 180");
function myHeading()
{
document.getElementById('header').write = (firstName + lastName);
}
The JavaScript code that should have access to certain DOM elements, has to come after the elements in HTML, otherwise the elements are not generated in DOM yet (assuming the JavaScript code you wrote is in
finalProj.js
):<body> <form name = "myForm"> <h1 id="myHeader"></h1> </from> <!-- can access myHeader now --> <script type="text/javascript" src="finalProj.js"></script> </body>
Don't know about a
write
property, butinnerHTML
should do it:document.getElementById('myHeader').innerHTML = firstName + lastName;
And of course you have to call
myHeading()
too!
document.getElementById('myheader').innerHTML = "(" + firstName + ' ' + lastName + ")";
?
The ID you specified and the ID of the header it looks like you are trying to select don't match. You have:
<h1 id="myHeader"></h1>
and
document.getElementById('header').write = (firstName + lastName);
You need to change that to:
document.getElementById('myHeader').write = (firstName + lastName);
try something like this:
var firstName = "RicK";
var courseName = "WEB 180";
function myHeading() {
document.getElementById('header').innerHTML = firstName + " " + lastName;
}
The property you want is innerHTML
(and you can omit the parenthesis):
document.getElementById('myHeader').innerHTML = firstName + lastName;
精彩评论