[Go to site: main page, start]

0% found this document useful (0 votes)
4 views9 pages

JavaScript - DOM and Events Tutorial

This tutorial covers how JavaScript interacts with web pages through the Document Object Model (DOM) and events. It explains selecting, modifying, and creating DOM elements, as well as handling events like clicks and form submissions. Key concepts include event bubbling, delegation, and common beginner mistakes to avoid when working with the DOM.

Uploaded by

bit001924
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views9 pages

JavaScript - DOM and Events Tutorial

This tutorial covers how JavaScript interacts with web pages through the Document Object Model (DOM) and events. It explains selecting, modifying, and creating DOM elements, as well as handling events like clicks and form submissions. Key concepts include event bubbling, delegation, and common beginner mistakes to avoid when working with the DOM.

Uploaded by

bit001924
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JavaScript: DOM and Events Tutorial

This tutorial assumes you already know basic JavaScript syntax (variables, loops, functions). The focus
here is how JavaScript actually interacts with web pages using the DOM and events.

1. What is the DOM?


When a browser loads an HTML page, it converts it into a structured object model called the DOM
(Document Object Model).

Think of the DOM as a tree of elements:

<body>
<h1>Hello</h1>
<button>Click</button>
</body>

This becomes a tree like:

❖ document
➢ html
▪ body
• h1
• button

JavaScript can access this tree and:

• read elements
• modify them
• create new elements
• delete elements
• respond to user actions (events)

2. Selecting DOM Elements


JavaScript must first find an element before it can change it.

Select by id

<h1 id="title">Welcome</h1>

const title = [Link]("title");


[Link](title);

pg. 1
Select by selector

This is the most common way.

<p class="info">Hello</p>
<p class="info">World</p>

const firstInfo = [Link](".info");


[Link](firstInfo); // first match only

Select multiple elements

const allInfo = [Link](".info");


[Link](allInfo); // NodeList

You can loop through them:

[Link](p => {
[Link]([Link]);
});

3. Reading and Changing Content


Text Content

This sets text of an HTML element.

[Link] = "New Title";

HTML Content

.innerHTML will parse the given text as HTML.

[Link] = "<span style='color:red'>Red Title</span>";

Use .innerHTML carefully because it can introduce security issues if you insert user input.

4. Changing Styles

Direct style change

[Link] = "blue";
[Link] = "40px";

This is okay for quick changes, but not best practice for big styling.

pg. 2
5. Using CSS Classes (Recommended)

Adding or removing CSS classes with JavaScript allows you to change the appearance or behavior of a
webpage in response to user actions.

Add a class

[Link]("highlight");

Remove a class

[Link]("highlight");

Toggle a class (add if missing, remove if present)

[Link]("highlight");

Example HTML + CSS:

<style>
.highlight {
color: green;
font-weight: bold;
}
</style>

<h1 id="title">Hello</h1>

6. Changing Attributes

HTML attributes include src, href, disabled, value, etc.

Get attribute

const link = [Link]("a");


[Link]([Link]("href"));

Set attribute

[Link]("href", "[Link]

Example: disable a button

const btn = [Link]("button");


[Link] = true;

pg. 3
7. Creating and Adding Elements

Create a new element

const newP = [Link]("p");


[Link] = "This paragraph was created by JS!";

Add it to the page

[Link](newP);

Add inside a container

<div id="box"></div>

const box = [Link]("box");

const msg = [Link]("h2");


[Link] = "Hello from JS";

[Link](msg);

8. Removing Elements

Remove an element

[Link]();

Or remove from parent:

[Link](msg);

9. DOM Events (Core Concept)

An event is something that happens in the browser:

• clicking a button
• typing in an input
• submitting a form
• moving the mouse
• pressing a key
• loading a page

JavaScript can "listen" for events and respond.

pg. 4
10. Event Listener Syntax

[Link]("eventName", function() {
// code here
});

Example:

<button id="btn">Click Me</button>

const btn = [Link]("btn");

[Link]("click", function() {
alert("Button clicked!");
});

11. Using Arrow Functions (Cleaner)

[Link]("click", () => {
[Link]("Clicked!");
});

12. The Event Object


When an event occurs, JavaScript provides an event object containing details.

[Link]("click", (event) => {


[Link](event);
});

Common useful properties:

• [Link] → the element that triggered the event


• [Link] → event name (click, keydown, etc.)

Example:

[Link]("click", (e) => {


[Link]("You clicked:", [Link]);
});

pg. 5
13. Input Events (Typing in Textboxes)

<input id="nameInput" type="text" placeholder="Type your name">


<p id="output"></p>

const input = [Link]("nameInput");


const output = [Link]("output");

[Link]("input", () => {
[Link] = "You typed: " + [Link];
});

[Link]("input", () => {
[Link]("You typed:", [Link]);
});

• input: triggers immediately as you type


• change: triggers when you finish typing and click away

14. Form Submit Events


Forms refresh the page by default. JavaScript often prevents that.

<form id="myForm">
<input id="email" type="email" placeholder="Enter email">
<button type="submit">Submit</button>
</form>

<p id="msg"></p>

const form = [Link]("myForm");


const email = [Link]("email");
const msg = [Link]("msg");

[Link]("submit", (e) => {


[Link](); // stop page refresh

[Link] = "Submitted email: " + [Link];


});

pg. 6
15. Event Bubbling
Events in the DOM "bubble up" from the child to the parent.

Example:

<div id="container">
<button id="btn">Click</button>
</div>

[Link]("btn").addEventListener("click", () => {
[Link]("Button clicked");
});

[Link]("container").addEventListener("click", () => {
[Link]("Container clicked");
});

If you click the button, output is:

Button clicked
Container clicked

Because the click bubbles up.

16. Stopping Event Bubbling

[Link]("click", (e) => {


[Link]();
[Link]("Only button");
});

Now clicking button won’t trigger the container event.

pg. 7
17. Event Delegation
Instead of adding event listeners to many buttons, attach one listener to the parent.

Example:

<ul id="list">
<li>Apple</li>
<li>Banana</li>
</ul>

const list = [Link]("list");

[Link]("click", (e) => {


if ([Link] === "LI") {
[Link]("You clicked:", [Link]);
}
});

This works even if you later add more <li> items dynamically.

18. Mini Project: Dark Mode Toggle

HTML:

<button id="toggleMode">Toggle Dark Mode</button>

CSS:

<style>
.dark {
background: black;
color: white;
}
</style>

JavaScript:

const toggleBtn = [Link]("toggleMode");

[Link]("click", () => {
[Link]("dark");
});

pg. 8
20. Page Load Events
Sometimes your JavaScript runs before HTML is fully loaded.

Safe solution: run after DOM loads

[Link]("DOMContentLoaded", () => {
[Link]("DOM is ready!");
});

This ensures elements exist before selecting them.

21. Common Beginner Mistakes


Selecting an element that doesn't exist

const btn = [Link]("missing");


[Link]("click", () => {});

This crashes because btn is null.

Always check:

if (btn) {
[Link]("click", () => {});
}

Forgetting # or . in querySelector

[Link]("title"); // wrong
[Link]("#title"); // correct

Using innerHTML for everything

Use:

• textContent for plain text


• innerHTML only when necessary

22. Summary

When you write JavaScript for web pages, you are usually doing this cycle:

1. Select an element
2. Listen for an event
3. Respond by changing the DOM
pg. 9

You might also like