Important FAQ

What is the Document Object Model (DOM)?

The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of a webpage in a tree-like format, allowing developers to access, manipulate, and modify the document’s content, structure, and style dynamically through programming languages like JavaScript.

How do you select an element from the DOM?

To select an element from the DOM, you can use `getElementById` to target an element by its ID. Another option is to use `querySelector` to select an element using a CSS selector. Additionally, you can use `getElementsByClassName` or `getElementsByTagName` to select elements by their class or tag name.

What is event delegation in the context of the DOM, and why is it useful?

**Event delegation** is a technique in the DOM where a single event listener is added to a parent element to handle events from its child elements, taking advantage of **event bubbling** (when events propagate up the DOM tree). It is useful because it allows you to manage events efficiently, especially when dealing with dynamically added elements, and reduces memory consumption by avoiding multiple event listeners on individual child elements. This improves performance and simplifies code in scenarios with many elements needing event handling.

How do you manipulate an element's attributes and styles using the DOM?

To manipulate an element's attributes, you can use methods like `setAttribute()`, `getAttribute()`, or directly modify properties (e.g., `element.src`, `element.href`). For styles, you can modify the `style` property (e.g., `element.style.color = 'red';`) or apply CSS classes using `classList` (e.g., `element.classList.add('newClass')`).