JavaScript inside HTML

How scripts, DOM, and variables work together

Where JavaScript goes in HTML

JavaScript is written inside the <script> tag. It is usually placed at the end of the <body>.

<script>
  // JavaScript code here
</script>
  

Variables: const and let

JavaScript uses variables to store data.

const name = "Anna";
let count = 0;
count = count + 1;
  

The document object

document represents the whole HTML page. It allows JavaScript to access elements.

document.getElementById("output");
  

What is an element?

An element is a part of the HTML page (like a div, input, or paragraph).

const el = document.getElementById("demo");
el.textContent = "Hello!";
  

Connecting HTML and JavaScript

JavaScript reads HTML elements, changes them, and updates the page.

<input id="name">
<button onclick="show()">Click</button>
<p id="output"></p>

<script>
function show() {
  const value = document.getElementById("name").value;
  document.getElementById("output").textContent = value;
}
</script>
  

Events (user interaction)

Events are actions like clicks or typing.

button.onclick = function() {
  alert("Clicked!");
};
  

Summary