JavaScript Crash Course – Lesson 3: DOM Manipulation and Event Handling

The Document Object Model (DOM)

The DOM is a programming interface for HTML and XML documents. It represents the structure of a document as a tree-like hierarchy, allowing JavaScript to dynamically access and manipulate the content, structure, and style of a web page.

Selecting DOM Elements

JavaScript provides several methods to select elements from the DOM:

  1. By ID:
JavaScript
   let element = document.getElementById('myId');
  1. By Class Name:
JavaScript
   let elements = document.getElementsByClassName('myClass');
  1. By Tag Name:
JavaScript
   let elements = document.getElementsByTagName('div');
  1. Using CSS Selectors:
JavaScript
   let element = document.querySelector('.myClass');
   let elements = document.querySelectorAll('p');

Modifying DOM Elements

Once you’ve selected an element, you can modify its content, attributes, and styles:

  1. Changing Text Content:
JavaScript
   element.textContent = 'New text content';
  1. Modifying HTML:
JavaScript
   element.innerHTML = '<strong>Bold text</strong>';
  1. Changing Attributes:
JavaScript
   element.setAttribute('class', 'newClass');
  1. Modifying Styles:
JavaScript
   element.style.color = 'red';
   element.style.fontSize = '20px';

Creating and Removing Elements

You can dynamically add or remove elements from the DOM:

  1. Creating Elements:
JavaScript
   let newDiv = document.createElement('div');
   newDiv.textContent = 'New Div';
   document.body.appendChild(newDiv);
  1. Removing Elements:
JavaScript
   let elementToRemove = document.getElementById('removeMe');
   elementToRemove.parentNode.removeChild(elementToRemove);

Event Handling

Events are actions or occurrences that happen in the system you are programming, which the system tells you about so you can respond to them.

Adding Event Listeners

You can use the addEventListener method to handle events:

JavaScript
let button = document.getElementById('myButton');
button.addEventListener('click', function() {
    console.log('Button clicked!');
});

Common Types of Events

  1. Mouse Events: click, dblclick, mouseenter, mouseleave
  2. Keyboard Events: keydown, keyup, keypress
  3. Form Events: submit, change, focus, blur
  4. Window Events: load, resize, scroll

Event Object

When an event occurs, the browser creates an event object with details about the event:

JavaScript
button.addEventListener('click', function(event) {
    console.log('Button clicked at coordinates: ' + event.clientX + ', ' + event.clientY);
});

Practical Example: Interactive To-Do List

Let’s combine DOM manipulation and event handling to create a simple interactive to-do list:

JavaScript
<!DOCTYPE html>
<html>
<body>
    <h2>My To-Do List</h2>
    <input type="text" id="taskInput" placeholder="New task...">
    <button id="addTask">Add Task</button>
    <ul id="taskList"></ul>

    <script>
        let addTaskButton = document.getElementById('addTask');
        let taskInput = document.getElementById('taskInput');
        let taskList = document.getElementById('taskList');

        addTaskButton.addEventListener('click', function() {
            if (taskInput.value !== '') {
                let newTask = document.createElement('li');
                newTask.textContent = taskInput.value;

                let deleteButton = document.createElement('button');
                deleteButton.textContent = 'Delete';
                deleteButton.addEventListener('click', function() {
                    taskList.removeChild(newTask);
                });

                newTask.appendChild(deleteButton);
                taskList.appendChild(newTask);
                taskInput.value = '';
            }
        });
    </script>
</body>
</html>

Practice Exercise

Enhance the to-do list application:

  1. Add a “Complete” button next to each task that, when clicked, strikes through the task text.
  2. Implement the ability to edit existing tasks.
  3. Add local storage functionality to persist tasks between page reloads.

Conclusion

This lesson covered the basics of DOM manipulation and event handling in JavaScript. These concepts are fundamental to creating interactive web applications. In the next lesson, we’ll explore asynchronous JavaScript, including promises and async/await syntax.

Remember to experiment with these concepts by modifying the example code and creating your own interactive web pages!