DOM

Deep dive into the Document Object Model structure and manipulation.

Present State

The DOM (Document Object Model) is a programming interface for HTML and XML documents. It represents the structure of a document as a tree of nodes, enabling developers to access and manipulate content, structure, and styles of web pages using JavaScript.

Code Example

Example of accessing and modifying DOM elements:

DOM Manipulation

// Selecting an element
const heading = document.getElementById("main-heading");

// Changing text content
heading.textContent = "Updated Heading";

// Changing style
heading.style.color = "blue";

// Creating and appending a new element
const newParagraph = document.createElement("p");
newParagraph.textContent = "This is a new paragraph.";
document.body.appendChild(newParagraph);
          

This code demonstrates:

  • How to select elements from the DOM using getElementById.
  • Updating text content of a DOM node.
  • Modifying styles dynamically.
  • Creating and inserting new elements into the DOM.

Description

The Document Object Model (DOM) represents the page so that programs can change the document structure, style, and content. It treats an HTML or XML document as a tree structure where each node is an object representing a part of the document.

Key DOM manipulation techniques include:

  • Selectors: Methods like getElementById, querySelector, and getElementsByClassName are used to access elements.
  • Content Manipulation: You can change or retrieve text, HTML, and attributes using properties like textContent, innerHTML, and setAttribute.
  • Style Manipulation: CSS styles can be modified via the style property.
  • Element Creation: New elements can be created and inserted into the document using createElement, appendChild, and insertBefore.

Applications

  • Creating interactive web pages with dynamic content updates.
  • Implementing features like dropdowns, modals, sliders, and tabs.
  • Real-time form validation and user feedback.
  • Manipulating content in response to user events.
  • Building single-page applications (SPAs) without full page reloads.

Multiple Choice Questions

Q1: What does the DOM stand for?

  • A. Document Object Map
  • B. Data Object Model
  • C. Document Object Model
  • D. Data Oriented Module

Answer: C. Document Object Model

Q2: Which method is used to select an element by ID?

  • A. querySelector
  • B. getElementById
  • C. getElementByTagName
  • D. getElementsByClassName

Answer: B. getElementById

Q3: How can you change the text of an element?

  • A. element.value
  • B. element.innerHTML
  • C. element.textContent
  • D. element.text

Answer: C. element.textContent

Q4: Which method is used to create a new element in the DOM?

  • A. createElement
  • B. appendChild
  • C. insertElement
  • D. newElement

Answer: A. createElement