• Home
  • Tutorials
  • Python Tutorial 1
  • Python Tutorial 2
  • Python Tutorial 3
  • Python Tutorial 4
  • Python Tutorial 5
  • JavaScript Tutorial 1
  • JavaScript Tutorial 2
  • JavaScript Tutorial 3
  • JavaScript Tutorial 4
  • JavaScript Tutorial 5

DOM Manipulation and Event Handling

What is the DOM (Document Object Model)?

The Document Object Model (DOM) is a programming interface for web documents. When a web page is loaded, the browser creates a tree-like structure of the HTML elements, which JavaScript can use to dynamically interact with and update the page.

Key Concepts:

  • The DOM represents the structure of an HTML document as a tree of nodes.
  • JavaScript can:
    • Access HTML elements.
    • Change content, attributes, and styles dynamically.
    • Respond to user interactions like clicks or form submissions.

Example: Consider this HTML:

<!DOCTYPE html>
<html>
<head>
   <title>My Page</title>
</head>
<body>
   <h1 id="main-title">Hello, World!</h1>
</body>
</html>
With JavaScript, you can change the text inside the <h1> tag dynamically:

document.getElementById("main-title").textContent = "Welcome to JavaScript!";
 

Selecting Elements in the DOM

JavaScript provides several methods to select and interact with HTML elements:

  • getElementById( ) 
    Selects an element by its ID.

let title = document.getElementById("main-title");
console.log(title.textContent);  // Output: Hello, World!

  • querySelector( ) 
    Selects the first matching element based on a CSS selector.

let title = document.querySelector("#main-title");
console.log(title.textContent);  // Output: Hello, World!

  • querySelectorAll( ) 
    Selects all matching elements and returns a NodeList (similar to an array).

let items = document.querySelectorAll("li");
items.forEach(item => console.log(item.textContent));


Questions & Answers:

  • Q: How do you select an element by its ID in JavaScript?
    • A: Use the getElementById( ) method, e.g., document.getElementById("id).
  • Q: What is the difference between querySelector( ) and querySelectorAll( )?
    • A: querySelector( ) selects the first matching element, while querySelectorAll( ) selects all matching elements.

Changing Content and Style

You can use JavaScript to update the content and styles of HTML elements dynamically.

  • Changing Content:

let title = document.getElementById("main-title");
title.textContent = "JavaScript is Awesome!";

  • Changing Styles: Use the styyle property to modify CSS styles.

title.style.color = "blue";
title.style.fontSize = "36px";

Questions & Answers:

  • Q: How do you change the text inside an HTML element?
    • A: Use the textContent property, e.g., element.textContent = "New Text";.
  • Q: How can you dynamically change the color of an element?
    • A: Use the style property, e.g., element.style.color = "blue";. 

Event Handling Basics

What is an Event?
An event is an action or occurrence detected by the browser, such as a click, keypress, or mouse hover.

Adding Event Listeners: You can respond to events using addEventListener( ).

Example:

<button id="my-button">Click Me</button>
<script>
   let button = document.getElementById("my-button");
   button.addEventListener("click", function() {
       alert("Button clicked!");
   });
</script>
Common Event Types:

  • click: Fired when an element is clicked.
  • mouseover: Fired when the mouse pointer moves over an element.
  • keydown: Fired when a key is pressed on the keyboard.


Questions & Answers:

  • Q: What is an event in JavaScript?
    • A: An event is an action or occurrence (e.g., click, keypress) that JavaScript can respond to.
  • Q: How do you attach an event listener to a button?
    • A: Use addEventListener( ), e.g., button.addEventListener("click", callbackFunction).

Mini-Project: Interactive Color Changer

Objective:
Create a web page where clicking a button changes the background color randomly.

HTML:

<!DOCTYPE html>
<html>
<head>
   <title>Color Changer</title>
</head>
<body>
   <h1>Click the Button to Change Background Color</h1>
   <button id="color-button">Change Color</button>
   <script src="script.js"></script>
</body>
</html>

JavaScript:

let button = document.getElementById("color-button");

button.addEventListener("click", function() {
   let randomColor = `rgb(${Math.floor(Math.random() * 256)}, 
                          ${Math.floor(Math.random() * 256)}, 
                          ${Math.floor(Math.random() * 256)})`;
   document.body.style.backgroundColor = randomColor;
});
 

Explanation:

  • The Math.random( ) function generates random numbers for the RGB color components.
  • The style.backgroundColor property changes the background color of the <body> element.


Questions for Practice:

  • Q: How do you generate random numbers in JavaScript?
    • A: Use Math.random( ) to generate a number between 0 and 1, then scale it as needed.
  • Q: How do you change the background color of the document?
    • A: Use document.body.style.backgroundColor.

Practice Exercise: To-Do List with Event Handlers

Objective:
Create a simple to-do list where users can add tasks and mark them as complete.

HTML:

<!DOCTYPE html>
<html>
<head>
   <title>To-Do List</title>
</head>
<body>
   <h1>To-Do List</h1>
   <input id="task-input" type="text" placeholder="Enter a task">
   <button id="add-button">Add Task</button>
   <ul id="task-list"></ul>
   <script src="script.js"></script>
</body>
</html>
 

JavaScript:

let addButton = document.getElementById("add-button");
let taskInput = document.getElementById("task-input");
let taskList = document.getElementById("task-list");

addButton.addEventListener("click", function() {
   let taskText = taskInput.value;

   if (taskText !== "") {
       let newTask = document.createElement("li");
       newTask.textContent = taskText;

       newTask.addEventListener("click", function() {
           newTask.style.textDecoration = "line-through";
       });

       taskList.appendChild(newTask);
       taskInput.value = "";  // Clear the input
   }
});
 

Explanation:

  • Clicking the "Add Task" button creates a new list item with the task text.
  • Clicking a task in the list strikes it out by adding textDecoration: "line-through".


Questions for Practice:

  • Q: How do you create a new HTML element using JavaScript?
    • A: Use document.createElement( ). 
  • Q: How do you append a new element to an existing element?
    • A: Use parentElement.appendChild(newElement).

Conclusion

Recap:

  • The DOM allows JavaScript to dynamically manipulate web pages.
  • Events let you respond to user interactions like clicks and keypresses.
  • You can combine DOM manipulation and event handling to create interactive applications.

Next Steps:

  • Practice building more interactive elements.
  • In future tutorials, explore advanced topics like animations and working with APIs.


Questions & Answers for Recap:

  • Q: What method selects all matching elements in the DOM?
    • A: querySelectorAll( ).
  • Q: How do you attach a click event to an HTML button?
    • A: Use addEventListener("click", callback).

GoInnovateSoftware

Copyright © 2024 GoInnovateSoftware - All Rights Reserved.

Powered by GoDaddy

This website uses cookies.

We use cookies to analyze website traffic and optimize your website experience. By accepting our use of cookies, your data will be aggregated with all other user data.

Accept