Line At A Time
Lesson 7: A Script File
A Script File Add the third file and let JavaScript change the page.
index.html
1<!doctype html>
2<html>
3 <head>
4 <title>Scripts</title>
5 </head>
6 <body>
7 <h1 id="greeting">Hello!</h1>
8 <script src="script.js"></script>
9 </body>
10</html>
script.js
1const greeting = document.getElementById('greeting');
2greeting.textContent = 'Hello from JavaScript!';
Terminal
Every line, explained
<!doctype html>
<!doctype html> is the very first line of every real web page. It simply tells the browser "this is a modern HTML page"; it is a declaration, not a tag, so it never gets closed.
<html>
<html> is the root: every other tag on the page lives inside it. Intro to HTML skipped this wrapper; now you are writing pages the way the pros do.
<head>
<head> holds information ABOUT the page: its title, and links to other files. Nothing inside <head> is drawn on the page itself.
<title>Scripts</title>
<title> names the browser tab. Look at the tab bar of a real browser: every name you see there is one of these.
</head>
</head> closes the head. The visible part of the page comes next.
<body>
<body> holds everything you can actually see: all the tags you learned in Intro to HTML go in here.
<h1 id="greeting">Hello!</h1>
A new attribute: id is a name for ONE particular tag (unlike class, which many tags can share). JavaScript will use this name to find the heading.
<script src="script.js"></script>
<script src="script.js"></script> loads the JavaScript file. It sits at the END of the body so the page above it exists before the script runs; a script that looks for a tag that hasn't been built yet finds nothing.
</body>
</body> closes the body.
</html>
</html> closes the root tag. Nothing comes after it.
const greeting = document.getElementById('greeting');
document is JavaScript's handle on the page, and getElementById fetches ONE tag by its id attribute. This is the bridge between the files: HTML gives a tag a name, JavaScript grabs it by that name. The tag lands in a const, ready to be changed. (const and quotes work exactly as in Intro to JavaScript.)
greeting.textContent = 'Hello from JavaScript!';
textContent is the text inside the tag, and you can simply assign it something new. Run the page: the HTML file says Hello!, but by the time you see it, JavaScript has already swapped it. The page is no longer just a document; it is a program.