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
newParagraphelement as a child of thebodyelement.
- In the example, document.body.appendChild(newParagraph) adds the
Lessons in this chapter ยท How does JavaScript work in the browser?
- 1. How Do Browsers Work?
- 2. DOM (Document Object Model)
- 3. Browser Window Object
- 4. Window - window.screen
- 5. Window - window.location
- 6. Methods to Select HTML Elements - 1
- 7. How to Select HTML Elements - 2
- 8. Creating and Setting Attributes of HTML Elements
- 9. Events
- 10. Advanced Event Handling
- 11. Multiple-choice quiz
- 12. JSON(JavaScript Object Notation)
- 13. Promise
- 14. Async/Await Handling Asynchronous Processes
- 15. Cookies
- 16. Multiple-choice quiz
- 17. JavaScript Summary
Manipulating the DOM with JavaScript allows you to dynamically change the content of a web page.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help