본문으로 건너뛰기

DOM (Document Object Model)

DOM (Document Object Model)

The DOM is a way of representing the structure of a web page. It expresses all elements, attributes, and their relationships on the web page as objects.


JavaScript and the DOM

Think of a web page as a 'tree'.

The branches and leaves of this tree represent each element and content (titles, text, images, etc.) of the web page.

The DOM is like a map that expresses the structure of the tree and information about its branches and leaves.

JavaScript is the tool that manipulates and modifies this tree.

For instance, just as you can change the color of a specific leaf on a tree or add new leaves, with JavaScript, you can dynamically change the content and structure of a web page.


Code Example:

// How to select HTML elements
let titleElement = document.querySelector('h1'); // Selects the h1 element.

// Changing content
titleElement.textContent = 'This is a new title.';

// Adding a new element
let newParagraph = document.createElement('p');
newParagraph.textContent = 'This is a new paragraph.';
document.body.appendChild(newParagraph);

Key Objects and Methods in the DOM

  • document: Represents the entire web page as an object.

  • .querySelector(): Used to select a specific element on the web page.

  • .createElement(): Used to create a new element.

  • .appendChild(): Used to add the element in parentheses as a child of the element that called appendChild.

    • In the example document.body.appendChild(newParagraph), it adds the newParagraph element as a child of the body element.