Module 4

0% completed

In this module we will take a deep dive into DOM manipulation, which involves creating, updating and deleting HTML elements and setting event listeners. These skills form the basis of any interactive web page as this allows us to respond to user input and update the page accordingly.

We will also look at handling forms in JavaScript smoothly, by taking advantage of decades of browser development and the HTML5 specification. Before anything, lets dive into what exactly is DOM.

What is the DOM

The DOM (Document Object Model) is a programming interface for web documents. It represents the structure of a webpage in a tree-like format that the browser interprets. When a browser loads a webpage (an HTML document), it converts the HTML code into the DOM, enabling JavaScript or other scripting languages to interact with it. That means that whenever you visit a webpage or run your code on localhost, what you are seeing is the DOM.

The DOM is composed of nodes and objects, just as a webpage consists of text, elements, and attributes. As a developer, you can interact with the DOM using JavaScript through a variety of available DOM methods.

  • getElementById('id') - selects an element by its id.
  • querySelector('selector) - Selects the first element that matches a CSS selector.
  • document.querySelectorAll('selector') – Selects all elements that match a CSS selector.
  • element.textContent – Changes or retrieves the text inside an element.
  • element.innerHTML – Changes or retrieves the HTML content inside an element.
  • element.setAttribute('attribute', 'value') – Changes or sets an attribute on an element (e.g., changing the src of an image).
  • document.createElement('tag') – Creates a new HTML element.
  • parentElement.appendChild(childElement) – Appends a new child element to a parent.
  • parentElement.removeChild(childElement) – Removes a child element from its parent.
  • element.addEventListener('event', callback) – Attaches an event listener to an element (e.g., listening for a click event).
  • parentNode.insertBefore(newNode, referenceNode) - Allows you to insert a new DOM element before an existing one, as a child of a specified parent node.

In this module, we will demonstrate how to effectively use all these methods to manipulate and interact with the DOM.