What is the DOM?
Web documents have a programming interface called the Document Object Model (DOM). It offers a mechanism to change the web page’s contents and structure and portrays the web page in a hierarchical structure.
A Document Object Model of a web page is created by a web browser when the page is loaded, and scripting languages like JavaScript can access and modify this model. The document tree can be navigated and modified using a number of common methods and attributes provided by the DOM.
The web page’s elements are represented hierarchically by the DOM tree. A node in the tree stands in for each element. The document object, which stands in for the complete web page, serves as the tree’s root. The tag name, attributes, and child nodes are only a few of the characteristics that each node in the tree possesses.
The properties of these nodes can be accessed and changed using the DOM. By modifying the DOM tree, we can, for instance, change the text of a paragraph element or add a new element to the web page.
Example:
<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
</head>
<body>
<h1>My Web Page</h1>
<p>Hello World!</p>
<script>
// get the paragraph element
var p = document.getElementsByTagName("p")[0];
// change the text of the paragraph element
p.textContent = "Hello DOM!";
</script>
</body>
</html>
In this example, we use the getElementsByTagName method of the document object to get the first p element in the web page. We then change the text content of the element using the textContent property. This is just one of many ways to access and manipulate the DOM tree.