Skip to main content

Connecting JavaScript and Selecting Elements

JavaScript can add interaction to an HTML interface. Keep the page usable when supporting scripts fail.

Connect a script

Place this before the closing body tag:

<script src="js/app.js"></script>

Or use defer in the page head:

<script src="js/app.js" defer></script>

Select an element

<p id="status">Waiting for an action.</p>
const statusMessage = document.querySelector("#status");

if (statusMessage) {
  statusMessage.textContent = "JavaScript loaded.";
}

Use meaningful identifiers and check that an element exists before using it.

Check

  • Script path is correct.
  • Browser console has no error.
  • Text is inserted with textContent when HTML is unnecessary.
  • Core information remains available without the script.