What is the Document Object Model (DOM)?

The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects; that way, programming languages can interact with the page.

How do you select an element from the DOM?
  • By ID: Use getElementById().
  • By Class Name: Use getElementsByClassName().
  • By Tag Name: Use getElementsByTagName().
  • By Query Selector (single element): Use querySelector().
  • By Query Selector All (multiple elements): Use querySelectorAll().
What is event delegation in the context of the DOM, and why is it useful?

Event delegation is a technique in JavaScript where you add a single event listener to a parent element, rather than adding multiple event listeners to individual child elements. When an event occurs on a child element, the event bubbles up (propagates) to the parent element, where it can be captured and handled.

It is Useful for:

  • Performance: Instead of attaching event listeners to every child element (which can be inefficient for large or dynamic content), a single event listener on the parent can manage all events.
  • Dynamic Elements: It allows handling of events for dynamically added elements without needing to reassign event listeners each time an element is added to the DOM.
  • Cleaner Code: Managing events through the parent element leads to more maintainable and less redundant code.
How do you manipulate an element's attributes and styles using the DOM?
  • getAttribute() : Retrieves the value of a specified attribute.
  • setAttribute() : Sets or changes the value of an attribute.
  • removeAttribute() : Removes an attribute from an element.