Lecture

DOM (Document Object Model)

The DOM provides a way to represent the structure of a web page, encapsulating every element and attribute on the page, along with their relationships, as objects.


JavaScript and the DOM

Consider the components of a web page as a tree.

In this tree, the branches and leaves represent the web page's various elements and content (such as headings, text, and images).

The DOM acts as a map representing the tree's structure and the branches and leaves, while JavaScript serves as the tool to manipulate and modify this tree.

For example, just as you might change the color of a particular leaf (a specific element on a webpage) or add a new leaf, you can use JavaScript to dynamically change a web page's content and structure.


Code Example:

Manipulating a Web Page Using the DOM
// Method to select an HTML element const titleElement = document.querySelector('h1'); // Selects the h1 element // Modifying content titleElement.textContent = 'New h1 Title'; // Adding a new element const newParagraph = document.createElement('p'); newParagraph.textContent = 'A new paragraph using a p element'; document.body.appendChild(newParagraph);

Key Objects and Methods in the DOM

  • document: Represents the entire web page.

  • .querySelector(): Used to select specific elements from the web page.

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

  • .appendChild(): Used to add the element within the parentheses as a child to the element on which appendChild is invoked.

    • In the example, document.body.appendChild(newParagraph) adds the newParagraph element as a child of the body element.
Mission
0 / 1

Manipulating the DOM with JavaScript allows you to dynamically change the content of a web page.

True
False

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help

HTML
CSS
JavaScript
Loading...