Learn how to access and manipulate DOM elements using JavaScript by selecting them with IDs, classes, and tag names. Master the basics of DOM manipulation to create dynamic web pages.
In this section, we will explore how to access and manipulate elements on a web page using JavaScript. By selecting elements with IDs, classes, and tag names, you can dynamically change the content and style of your web pages. This is a crucial skill for creating interactive and engaging user experiences.
Before we dive into selecting elements, let’s briefly revisit the Document Object Model (DOM). The DOM is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as a tree of nodes, where each node is an object representing a part of the document.
Here’s a simple representation of a DOM tree for a basic HTML document:
graph TD; A[Document] A --> B[html] B --> C[head] B --> D[body] C --> E[title] D --> F[h1] D --> G[p] D --> H[div] H --> I[span]
In this diagram, each element in the HTML is a node in the tree. The document
object is the root, and it branches out to html
, head
, body
, and so on.
The most straightforward way to select an element is by its ID. Every HTML element can have an id
attribute, which must be unique within the document. This uniqueness makes it easy to select a specific element.
document.getElementById()
The document.getElementById()
method is used to select an element by its ID. It returns the element object representing the first element in the document with the specified ID.
Example:
Let’s say we have the following HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Example Page</title>
</head>
<body>
<h1 id="main-heading">Welcome to My Website</h1>
<p>This is a simple paragraph.</p>
</body>
</html>
To select the <h1>
element with the ID main-heading
, you would use:
let heading = document.getElementById('main-heading');
console.log(heading); // Outputs: <h1 id="main-heading">Welcome to My Website</h1>
Once you have selected an element, you can manipulate it. For example, you can change its text content:
heading.innerText = "Hello, World!";
This changes the text inside the <h1>
element to “Hello, World!”.
Sometimes, you want to select multiple elements that share the same class. Classes are used to group elements for styling and scripting purposes.
document.getElementsByClassName()
The document.getElementsByClassName()
method returns a live HTMLCollection of elements with the specified class name. This means that if the document changes, the collection is automatically updated.
Example:
Consider the following HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Example Page</title>
</head>
<body>
<div class="content">Content Block 1</div>
<div class="content">Content Block 2</div>
<div class="content">Content Block 3</div>
</body>
</html>
To select all <div>
elements with the class content
, you would use:
let contentBlocks = document.getElementsByClassName('content');
console.log(contentBlocks); // Outputs: HTMLCollection of <div> elements
You can loop through the HTMLCollection to manipulate each element:
for (let i = 0; i < contentBlocks.length; i++) {
contentBlocks[i].style.color = 'blue';
}
This changes the text color of all elements with the class content
to blue.
Selecting elements by tag name is useful when you want to target all elements of a specific type, such as all paragraphs or all images.
document.getElementsByTagName()
The document.getElementsByTagName()
method returns a live HTMLCollection of elements with the specified tag name.
Example:
Here’s some HTML with multiple paragraph elements:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Example Page</title>
</head>
<body>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
</body>
</html>
To select all <p>
elements, you would use:
let paragraphs = document.getElementsByTagName('p');
console.log(paragraphs); // Outputs: HTMLCollection of <p> elements
You can iterate over the HTMLCollection to change each paragraph:
for (let i = 0; i < paragraphs.length; i++) {
paragraphs[i].style.fontWeight = 'bold';
}
This makes the text in all paragraph elements bold.
When selecting elements, it’s important to understand the return types:
document.getElementById()
returns a single element object or null
if no element with the specified ID exists.document.getElementsByClassName()
and document.getElementsByTagName()
return an HTMLCollection, which is a live collection of elements. This means it updates automatically if the document changes.Let’s put this all together in a practical example. We’ll create a simple web page and use JavaScript to manipulate its elements.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Interactive Page</title>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<h1 id="page-title">My Interactive Page</h1>
<div class="content">This is a content block.</div>
<div class="content">Another content block.</div>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button id="change-title">Change Title</button>
<button id="highlight-content">Highlight Content</button>
</body>
</html>
JavaScript:
// Select the title by ID and change its text
let title = document.getElementById('page-title');
document.getElementById('change-title').addEventListener('click', function() {
title.innerText = "Title Changed!";
});
// Select all content blocks by class and highlight them
let contentBlocks = document.getElementsByClassName('content');
document.getElementById('highlight-content').addEventListener('click', function() {
for (let i = 0; i < contentBlocks.length; i++) {
contentBlocks[i].classList.toggle('highlight');
}
});
// Select all paragraphs by tag name and change their font style
let paragraphs = document.getElementsByTagName('p');
for (let i = 0; i < paragraphs.length; i++) {
paragraphs[i].style.fontStyle = 'italic';
}
Now it’s your turn! Try modifying the code above to:
In this section, we’ve learned how to select elements by ID, class, and tag using JavaScript. These methods allow you to access and manipulate elements on your web page, making it possible to create dynamic and interactive experiences. Remember that getElementById()
returns a single element, while getElementsByClassName()
and getElementsByTagName()
return live HTMLCollections.
For more information on DOM manipulation, check out these resources: