开发者

Creating a website on the fly using getElementById?

开发者 https://www.devze.com 2023-01-28 23:41 出处:网络
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 th

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);
} 


  1. 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>
    
  2. Don't know about a write property, but innerHTML 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;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号