Sobes.tech
Intern

Why is the Document Object Model (DOM) needed?

sobes.tech AI

Answer from AI

The DOM allows programs (such as JavaScript) to access the content, structure, and styles of web documents (HTML, XML, SVG) and modify them. It is an API that represents the document as a structured tree of nodes.

Main functions of the DOM:

  • Document representation: Converts the source code of the document into an object representation.
  • Access: Allows finding and selecting elements within the document.
  • Manipulation: Enables changing the content, attributes, and styles of elements, as well as adding or removing elements.
  • Event handling: Allows binding handlers to events (click, hover, etc.) on document elements.

Example of working with DOM in JavaScript:

// Get element by its id
const element = document.getElementById('myElement');

// Change its text
element.textContent = 'New text';

// Add a new class
element.classList.add('new-class');

// Create a new element
const newDiv = document.createElement('div');
newDiv.textContent = 'Hello!';

// Append the new element to the document body
document.body.appendChild(newDiv);