HTML Scripts
The script element holds JavaScript code inside a page. JavaScript is the browser's instruction language.
Writing text with a script
The write call adds text where the script sits in the page. The written line becomes normal page text.
<p>First line.</p>
<script>document.write("Second line from the script.");</script>
<p>Third line.</p>Changing a paragraph
The getElementById call finds the paragraph through its id value. Setting its text replaces the old words with new ones.
<p id="note">Old note.</p>
<script>document.getElementById("note").textContent = "Fresh note.";</script>Text for browsers without scripts
The noscript element holds text for browsers with scripts turned off. Scripts run in this browser, so that text stays hidden here.
<noscript>Scripts are off.</noscript>
<p>Scripts are on for this page.</p>Example
<!DOCTYPE html>
<html lang="en">
<head>
<title>Script Demo</title>
</head>
<body>
<h1>Script Demo</h1>
<p id="status">Waiting for the script.</p>
<script>document.getElementById("status").textContent = "The script ran and changed this line.";</script>
<p>The page is ready.</p>
</body>
</html>Key points
- Script: an element that holds code the browser runs as the page loads
- A script brings instructions into the page, so the page can change while it loads
- document.write: a call that writes text into the page at the script spot
- getElementById: a call that finds one element through its id value
- noscript: an element whose text shows only when scripts are off or missing
In this example, the paragraph starts with a waiting message and an id of status. The script element sits after the paragraph in the body. Its code finds the paragraph through the id and replaces its text. The rendered page shows the new line, because the browser ran the script while loading. The last paragraph is plain text and never changes.
Note
The JavaScript course teaches this language in depth, and this lesson is a first look only
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What happens to noscript content when scripts run normally?