DOM Selection in JavaScript
DOM (Document Object Model) selection allows you to access and manipulate HTML elements on a webpage. Let me explain the main methods with examples.
Main DOM Selection Methods
1. getElementById()
Selects an element by its ID attribute.
// HTML: <div id="header">Welcome</div>
const header = document.getElementById('header');
header.style.color = 'blue';
2. getElementsByClassName()
Selects all elements with a specific class name.
// HTML: <p class="highlight">Text 1</p><p class="highlight">Text 2</p>
const highlights = document.getElementsByClassName('highlight');
highlights[0].innerHTML = "First highlighted text";
3. getElementsByTagName()
Selects all elements with a specific tag name.
// Selects all paragraph elements
const paragraphs = document.getElementsByTagName('p');
console.log(paragraphs.length); // Number of paragraphs
4. querySelector()
Returns the first element that matches a CSS selector.
// HTML: <div class="container"><p>First</p><p>Second</p></div>
const firstPara = document.querySelector('.container p');
firstPara.style.fontWeight = 'bold';
5. querySelectorAll()
Returns all elements that match a CSS selector.
// Selects all list items in an unordered list
const listItems = document.querySelectorAll('ul li');
listItems.forEach(item => {
item.style.backgroundColor = 'yellow';
});
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM Selection Examples</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
}
.container {
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
h1 {
color: #2c3e50;
border-bottom: 2px solid #3498db;
padding-bottom: 10px;
}
.card {
border: 1px solid #ddd;
padding: 15px;
margin: 10px 0;
border-radius: 5px;
}
.highlight {
background-color: #ffffcc;
padding: 5px;
}
button {
background-color: #3498db;
color: white;
border: none;
padding: 8px 15px;
border-radius: 4px;
cursor: pointer;
margin: 5px;
}
button:hover {
background-color: #2980b9;
}
.output {
background-color: #f8f9fa;
padding: 15px;
border-left: 4px solid #3498db;
margin-top: 20px;
}
</style>
</head>
<body>
<div class="container">
<h1>DOM Selection Methods</h1>
<div class="card">
<h2 id="main-heading">getElementById Example</h2>
<button onclick="changeHeading()">Change Heading Color</button>
</div>
<div class="card">
<h2>getElementsByClassName Example</h2>
<p class="highlight">First highlighted paragraph.</p>
<p class="highlight">Second highlighted paragraph.</p>
<button onclick="changeHighlights()">Change Highlights</button>
</div>
<div class="card">
<h2>getElementsByTagName Example</h2>
<p>First paragraph with tag selection.</p>
<p>Second paragraph with tag selection.</p>
<button onclick="countParagraphs()">Count Paragraphs</button>
</div>
<div class="card">
<h2>querySelector Example</h2>
<div class="demo">
<p>First paragraph in demo div.</p>
<p>Second paragraph in demo div.</p>
</div>
<button onclick="selectFirst()">Select First Paragraph in Div</button>
</div>
<div class="card">
<h2>querySelectorAll Example</h2>
<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ul>
<button onclick="colorListItems()">Color List Items</button>
</div>
<div class="output">
<h3>Output:</h3>
<div id="output-content">Interact with the buttons to see results here.</div>
</div>
</div>
<script>
function changeHeading() {
const heading = document.getElementById('main-heading');
heading.style.color = heading.style.color === 'red' ? '#2c3e50' : 'red';
document.getElementById('output-content').innerHTML =
`Changed heading color to ${heading.style.color}`;
}
function changeHighlights() {
const highlights = document.getElementsByClassName('highlight');
for (let i = 0; i < highlights.length; i++) {
highlights[i].style.backgroundColor =
highlights[i].style.backgroundColor === 'lightgreen' ? '#ffffcc' : 'lightgreen';
}
document.getElementById('output-content').innerHTML =
`Changed ${highlights.length} highlighted elements`;
}
function countParagraphs() {
const paragraphs = document.getElementsByTagName('p');
document.getElementById('output-content').innerHTML =
`This page contains ${paragraphs.length} paragraph elements`;
}
function selectFirst() {
const firstPara = document.querySelector('.demo p');
firstPara.style.fontWeight = firstPara.style.fontWeight === 'bold' ? 'normal' : 'bold';
document.getElementById('output-content').innerHTML =
`Applied style to: "${firstPara.textContent}"`;
}
function colorListItems() {
const listItems = document.querySelectorAll('li');
listItems.forEach(item => {
item.style.color = item.style.color === 'purple' ? 'black' : 'purple';
});
document.getElementById('output-content').innerHTML =
`Changed color of ${listItems.length} list items`;
}
</script>
</body>
</html>
Key Points to Remember
- getElementById() returns a single element
- getElementsByClassName() and getElementsByTagName() return live HTMLCollections
- querySelector() returns the first matching element
- querySelectorAll() returns a static NodeList
- CSS selectors in querySelector methods allow for complex selections
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.