JavaScript and the DOM
What Is It?
JavaScript can change a page after it opens. The DOM is the browser’s representation of your page elements.
What the Tags Mean
script: holds JavaScript.button: starts an action.id: lets the script find one element.textContent: reads or changes an element’s text.
Example 1
Save each example as index.html and open it in your browser. Each code block is a complete page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript and the DOM</title>
</head>
<body>
<button id="hello" type="button">Say hello</button>
<p id="message">Waiting...</p>
<script>
document.getElementById("hello").addEventListener("click", () => {
document.getElementById("message").textContent = "Hello!";
});
</script>
</body>
</html>Browser preview
What you see: Click Say hello. Waiting... changes to Hello!. The script performs the change.
Example 2: Another Use
You can also change text as soon as the script runs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript and the DOM</title>
</head>
<body>
<p id="name">Guest</p>
<script>
document.getElementById("name").textContent = "Asha";
</script>
</body>
</html>Browser preview
Simple Tip
Put these scripts after the elements they use. Use textContent when inserting plain text.
Try It Yourself
Change the button message to Welcome to my page.