Introduction to DOM:
- The Document Object Model (DOM) connects web pages to scripts or programming languages by representing the structure of a document, such as the HTML representing a web page.
- The DOM represents a document with a logical tree. Each branch of the tree ends in a node, and each node contains objects.
- DOM methods allow programmatic access to the tree. With them, you can change the document's structure, style, or content.
- Nodes can also have event handlers attached to them. Once an event is triggered, the event handlers get executed.
What is Document?
- A web page is a document that can be either displayed in the browser window or as the HTML source.
- In both cases, it is the same document but the Document Object Model (DOM) representation allows it to be manipulated.
- As an object-oriented representation of the web page, it can be modified with a scripting language such as JavaScript.
What is a DOM tree?
- A DOM tree is a tree structure whose nodes represent an HTML or XML document's contents. Each HTML or XML document has a DOM tree representation. For example, consider the following document:
<html lang="en">
<head>
<title>My Document</title>
</head>
<body>
<h1>Header</h1>
<p>Paragraph</p>
</body>
</html>
It has a DOM tree that looks like this:
JavaScript getElementById() Method
The getElementById() method of the document object returns an HTML element with the specified id.
Hereβs the syntax of the getElementById() method:
const element = document.getElementById(id);
In this syntax:
`id` is a string that represents the id of the element to select.
Note that the method matches ID case-sensitively. For example, the 'root' and 'Root' are different.
If the document has no element with the specified id, the getElementById() method returns null.
JavaScript getElementById() method example
Suppose you have a document with two p elements:
<p id="first">Hi, There!</p>
<p>JavaScript is fun.</p>
The following code shows how to get the element with the id first:
const elem = document.getElementById("first");
See the following demo:
References:
https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model
https://www.javascripttutorial.net/javascript-dom/


Top comments (0)