Build a website on the fly with getElementById?

I am trying to create a website on the fly using JavaScript, but cannot get my getElementById function to work correctly. I joked a bit, found examples and tried to get them to work without success (most of them did not use an external .js file). The following is the code for 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="myHeader"></h1>

JavaScript:

var firstName = ("RicK");
var courseName = ("WEB 180");

function myHeading()
{
document.getElementById('header').write = (firstName + lastName);
} 
+3
source share
5 answers
  • The JavaScript code that must have access to certain DOM elements must come after the elements in the HTML, otherwise the elements have not yet been generated in the DOM (provided that 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>
    
  • write, innerHTML :

    document.getElementById('myHeader').innerHTML = firstName + lastName;
    

    , , myHeading()!

+6
document.getElementById('myheader').innerHTML = "(" + firstName + ' ' + lastName + ")";

?

+2

The identifier you specified and the identifier of the header, which it looks like your choice, do not match. You have:

<h1 id="myHeader"></h1>

and

document.getElementById('header').write = (firstName + lastName);

You need to change this to:

document.getElementById('myHeader').write = (firstName + lastName);
+2
source

try something like this:

var firstName = "RicK";
var courseName = "WEB 180";

function myHeading() {
    document.getElementById('header').innerHTML = firstName + " " + lastName;
} 
+1
source

Required property innerHTML(and you can omit the brackets):

document.getElementById('myHeader').innerHTML = firstName + lastName;
+1
source

Source: https://habr.com/ru/post/1778423/


All Articles