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:
// 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 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.