JavaScript DOM Introduction

Understanding how JavaScript interacts with web pages

🌐 What is the DOM?

The DOM (Document Object Model) is how JavaScript can access and change HTML elements on a web page. Think of it as a bridge between your HTML and JavaScript.


// This is how JavaScript talks to HTML
document.getElementById("myText").innerHTML = "Hello from JavaScript!";
                                    

HTML:

<p id="myText">Original text</p>

Result:

Hello from JavaScript!

Key DOM Concepts

🎯

Finding Elements

Locate HTML elements to work with

document.getElementById("myId")
✏️

Changing Content

Update text and HTML inside elements

element.innerHTML = "New text"
🎨

Changing Styles

Modify colors, sizes, and appearance

element.style.color = "red"
👆

Handling Events

Respond to clicks, typing, and more

element.onclick = function() {}

🔹 Your First DOM Example

Let's make a button that changes text when clicked:

<!DOCTYPE html>
<html>
<body>
    <h1 id="demo">Hello World!</h1>
    <button onclick="changeText()">Click Me</button>

    <script>
    function changeText() {
        document.getElementById("demo").innerHTML = "Text Changed!";
    }
    </script>
</body>
</html>

Try it:

Hello World!

🔹 Common DOM Tasks

Here are the most common things you'll do with the DOM:

🔸 Change Text Content

// Find element and change its text
let element = document.getElementById("myParagraph");
element.innerHTML = "This is new text!";

🔸 Change Element Style

// Make text red and bigger
let element = document.getElementById("myText");
element.style.color = "red";
element.style.fontSize = "20px";

🔸 Hide/Show Elements

// Hide an element
document.getElementById("myDiv").style.display = "none";

// Show an element
document.getElementById("myDiv").style.display = "block";

🔹 Interactive Example

Try this color changer:

<p id="colorText">This text will change color!</p>
<button onclick="changeColor()">Change Color</button>

<script>
function changeColor() {
    let colors = ["red", "blue", "green", "purple", "orange"];
    let randomColor = colors[Math.floor(Math.random() * colors.length)];
    document.getElementById("colorText").style.color = randomColor;
}
</script>

Try it:

This text will change color!

🧠 Test Your Knowledge

What does DOM stand for?