In JavaScript, the Document Object Model (DOM) allows you to create dynamic and interactive web pages by manipulating elements.
What is the Document Object Model (DOM)?
The Document Object Model (DOM) allows you to select and modify elements, create and remove elements, and manipulate element styles in the document.
DOM represents the structure of an HTML document as a tree-like structure.
The document is the root of the tree and contains one child node that is <html> element.
Within the <html> element, there are two children: the <head> and <body> elements.
The <head> and <body> elements contain their respective children.
Selecting Elements in the Document
The DOM provides the following methods to select elements.
getElementById(): selects the element by its unique id
HTML Structure:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<p id="paragraph">This is paragraph.</p>
</body>
</html>Select the element by its id:
const paragraph = document.getElementById("paragraph");
console.log(paragraph);Output:
Here, document.getElementById("paragraph") method searches the entire HTML document for an element with the id of paragraph. It returns a reference to that element (if found), or null if no such element exists.
getElementsByClassName(): selects elements by their class name
HTML Structure:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1 class="text">This is heading.</h1>
<p class="text">This is paragraph.</p>
</body>
</html>