JavaScript and HTML

Including JavaScript in HTML

JavaScript code can be embedded directly in an HTML file using<script> tags, or linked externally through a file. Inline scripts can appear in the <head> or at the bottom of the <body>. Scripts at the bottom improve page load time by ensuring HTML loads before JavaScript runs.

<!-- Inline script -->
<script>
  console.log("Page loaded");
</script>
<!-- External script -->
<script src="app.js"></script>

Outputting to HTML

JavaScript can display content in a web page using methods likedocument.write() (not recommended in modern use),innerHTML (commonly used), ortextContent. These allow dynamic updates such as showing live data, user feedback, or conditional content.

document.getElementById("message").innerHTML = "Welcome!";
document.write("This is a legacy method.");

DOM Manipulation

DOM stands for Document Object Model, which is a programming interface that represents the structure of an HTML or XML document as a tree of objects, allowing scripts to update content, style, and structure dynamically.

The DOM lets you programmatically access every element on the page. JavaScript provides powerful methods to read, change, and respond to elements. For example, you can modify a paragraph's text, change an image's source, or create new HTML elements dynamically.

document.getElementById("title").innerText = "Updated!";
document.querySelector(".box").style.backgroundColor = "lightblue";

Event Handling

JavaScript allows elements to respond to user input such as clicks, form submissions, keyboard presses, and more. Inline event attributes like onclick can be used, but attaching handlers viaaddEventListener() is cleaner and more flexible.

<button id="clickMe">Click</button>

<script>
  document.getElementById("clickMe").addEventListener("click", () => {
    alert("You clicked the button!");
  });
</script>

External Scripts

Placing JavaScript in separate .js files promotes clean separation of structure (HTML), style (CSS), and behavior (JS). This helps with code organization, caching, and collaboration in larger projects.

<!-- HTML -->
<script src="main.js"></script>
// main.js
console.log("External JS loaded");

Best Practices

  • Use addEventListener() instead of inline handlers
  • Wrap JS in DOMContentLoaded to ensure HTML is ready
  • Avoid document.write() — use innerHTML or DOM APIs
  • Place <script> tags at the end of the body
document.addEventListener("DOMContentLoaded", () => {
  console.log("DOM ready!");
});

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic