Overview
Last updated
Last updated
The Document Object Model (DOM) is the programming interface for web documents. It represents the web page so that programs can change the document structure, style, and content.
When a web page is loaded, the browser creates a Document Object Model of the page. The HTML DOM model is constructed as a tree of Objects:
The Document Object is the root of the tree
All elements, their attributes, and text content are represented as objects within the tree
Each object can have child objects, representing the elements or nodes within it
With the DOM, JavaScript can access and manipulate all the elements on a web page. This means that JavaScript can:
Change the content of an HTML element
Change the attributes of HTML elements
Add or remove HTML elements and content
React to HTML events like clicks or page loads
And more!
In essence, the DOM allows you to interact with and modify a web page using JavaScript.
Here's a basic introduction to working with the DOM in JavaScript:
Accessing Elements:
To access an element in the DOM, you can use the document
object, followed by the method to access the element. For example, to access an element with an id
attribute of "my-element", you can use document.getElementById("my-element")
. This method returns the element as an object that you can then work with.
Modifying Elements:
Once you have accessed an element in the DOM, you can modify its content or attributes. For example, you can change the text content of an element using the textContent
property. To change the background color of an element, you can use the style.backgroundColor
property.
Adding and Removing Elements:
You can also add new elements to the DOM or remove existing ones. To create a new element, you can use the createElement
method and then add it to the document using the appendChild
method. To remove an element, you can use the removeChild
method.
Event Handling:
You can also add event listeners to elements to respond to user interaction. For example, you can add a click event listener to a button element using the addEventListener
method.
Here's an example code snippet that demonstrates some of these basic concepts: