DOM (Document Object Model)
DOM
is a way of representing the structure of a web page, where every element and attribute in the web page, along with their relationships, are represented as objects.
JavaScript and the DOM
Think of the components of a web page as a tree.
The branches and leaves
of this tree represent the elements and content
(titles, text, images, etc.) of the web page.
The DOM is a map that represents the structure and information about the branches and leaves, while JavaScript is the tool that manipulates and modifies this tree.
For example, just like changing the color of a specific leaf (a specific element of the web page) or adding a new leaf, JavaScript allows you to dynamically change the content and structure of a web page.
Code Example:
// How to select HTML elements
const titleElement = document.querySelector('h1'); // Selects the h1 element
// Changing 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);
Important Objects and Methods in the DOM
-
document
: Represents the entire web page. -
.querySelector()
: Used to select a specific element in the web page. -
.createElement()
: Used to create a new element. -
.appendChild()
: Adds the element inside the parentheses as a child to the element on which appendChild was called.- In the example, document.body.appendChild(newParagraph) adds the
newParagraph
element as a child to thebody
element.
- In the example, document.body.appendChild(newParagraph) adds the
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.