DOM (Document Object Model) and Finding Elements in an HTML Page
The Document Object Model (DOM) is a tree-like data structure that represents the structure of an HTML document. It’s used by web browsers and JavaScript code to interact with the contents of an HTML page.
In this example, we’ll use DOM to find elements on a main HTML page. We’ll assume you have an HTML file called index.html
:
<!DOCTYPE html>
<html>
<head>
<title>Main Page</title>
</head>
<body>
<h1 id="header">Main Page Header</h1>
<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
</ul>
<div id="content">
This is the main content area.
</div>
</body>
</html>
Finding Elements using DOM
To find elements on an HTML page, you can use the document
object and its methods. Here are some examples:
- Getting an element by ID: Use the
getElementById()
method to retrieve an element with a specific ID.const header = document.getElementById("header"); console.log(header.textContent); // Output: "Main Page Header"
- Getting all elements of a specific type: Use the
getElementsBy
method to retrieve all elements of a specific type (e.g.,<h1>
,<ul>
, etc.).const h1Elements = document.getElementsByTagName("h1"); console.log(h1Elements.length); // Output: 1
- Getting an element by class: Use the
getElementsByClassName()
method to retrieve all elements with a specific class.const listItems = document.getElementsByClassName("list-item"); console.log(listItems.length); // Output: 2
- Using querySelector(): The
querySelector()
method is a more powerful way to select elements based on CSS selectors.const contentDiv = document.querySelector("#content"); console.log(contentDiv.innerHTML); // Output: "This is the main content area."
- Using querySelectorAll(): The
querySelectorAll()
method returns a collection of elements that match the specified selector.const listItems = document.querySelectorAll("#list li"); console.log(listItems.length); // Output: 2