Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Take A QuizChallenge yourself and boost your learning! Start the quiz now to earn credits.
Take A QuizUnlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
Take A Quiz
🧩 Introduction: Getting
Hands-On with the DOM
Now that you understand what the DOM is and how JavaScript
interacts with it, the next step is learning how to select and access
elements from your HTML structure. This is the foundation of everything
you’ll do in dynamic web development — whether it’s changing content, adding
styles, handling clicks, or creating new elements.
In this chapter, we’ll explore:
🛠️ DOM Selection Methods
Overview
There are five core methods to select elements in the
DOM:
Method |
Description |
Return Type |
getElementById() |
Selects one element by
ID |
Single Element |
getElementsByClassName() |
All elements
with a given class |
HTMLCollection |
getElementsByTagName() |
All elements with a
specific tag |
HTMLCollection |
querySelector() |
First element
that matches a CSS selector |
Single
Element |
querySelectorAll() |
All elements that
match a CSS selector |
NodeList |
🔍 1. Selecting by ID —
getElementById()
html
<h1
id="main-title">Welcome!</h1>
javascript
const
title = document.getElementById('main-title');
title.textContent
= 'Hello from JS!';
🔎 2. Selecting by Class —
getElementsByClassName()
html
<p
class="intro">Intro 1</p>
<p
class="intro">Intro 2</p>
javascript
const
intros = document.getElementsByClassName('intro');
console.log(intros);
// HTMLCollection
for
(let i = 0; i < intros.length; i++) {
intros[i].style.color = 'blue';
}
🔎 3. Selecting by Tag —
getElementsByTagName()
html
<ul>
<li>Apple</li>
<li>Banana</li>
</ul>
javascript
const
listItems = document.getElementsByTagName('li');
for
(let item of listItems) {
item.style.listStyleType = 'square';
}
🧠 Key Differences:
HTMLCollection vs NodeList
Feature |
HTMLCollection |
NodeList |
Live updates |
✅ Yes |
❌ No |
Loops |
for, forEach
(after conversion) |
forEach
available |
Conversion to array |
Array.from() or spread
([...collection]) |
Same |
🧠 Example: Converting to
Array
javascript
const
items = document.getElementsByClassName('product');
const
itemsArray = [...items]; // or Array.from(items)
itemsArray.forEach(item
=> item.classList.add('highlight'));
🌟 4. Selecting with CSS
Selectors — querySelector()
html
<p
class="description">Hello!</p>
javascript
const
desc = document.querySelector('.description');
desc.textContent
= 'Updated!';
🌟 5. Selecting Multiple
Elements — querySelectorAll()
html
<ul>
<li
class="link">Home</li>
<li
class="link">About</li>
<li
class="link">Contact</li>
</ul>
javascript
const
links = document.querySelectorAll('.link');
links.forEach(link
=> link.style.fontWeight = 'bold');
📐 Advanced Selectors
🔹 Attribute Selector
html
<input
type="text" name="email" />
javascript
document.querySelector('input[name="email"]');
🔹 nth-child
javascript
document.querySelector('ul
li:nth-child(2)');
🔹 Descendant Selector
javascript
document.querySelector('.card
.title');
🧪 Best Practices for
Selecting Elements
🧠 Real Example: DOM
Selection in a Modal
html
<div
class="modal hidden" id="infoModal">
<p>This is a modal.</p>
<button
class="close-btn">Close</button>
</div>
javascript
const
modal = document.getElementById('infoModal');
const
closeBtn = document.querySelector('.close-btn');
closeBtn.addEventListener('click',
() => {
modal.classList.add('hidden');
});
❗ Common Mistakes
Mistake |
Fix |
Using ID with
querySelector() and forgetting # |
Use '#elementId' |
Using getElementById() on classes |
Use getElementsByClassName()
or querySelector() |
Using forEach on
HTMLCollection directly |
Convert it to array
first |
DOM elements not found |
Make sure
script runs after DOM loads |
🚦 Bonus: Wait for DOM to
Load
Always make sure your code runs after the HTML has
loaded:
javascript
document.addEventListener('DOMContentLoaded',
() => {
// Safe to select and manipulate elements
here
});
OR place your <script> tag just before
</body>
📋 Summary Table
Method |
Returns |
Supports |
Use Case |
getElementById() |
Element |
ID only |
Fast single-element
selection |
getElementsByClassName() |
HTMLCollection |
Class |
Grouped
elements |
getElementsByTagName() |
HTMLCollection |
Tags |
Mass selection |
querySelector() |
Element |
Full CSS selectors |
Flexible,
first match |
querySelectorAll() |
NodeList |
Full CSS selectors |
Multiple matches |
📍 Summary: Key Takeaways
Once you're confident with selecting elements, you're ready
to move into modifying content and attributes — the next step in DOM
mastery.
A: The DOM (Document Object Model) is a
tree-like structure that represents your web page. JavaScript can access and
modify this structure to change elements, styles, content, and more—dynamically
and in real-time.
A: Not exactly. The DOM is a Web API provided by
the browser, but JavaScript interacts with it using built-in methods like
getElementById, querySelector, and addEventListener.
Use DOM methods like:
document.getElementById('id')
document.querySelector('.class')
document.querySelector('tag')
element.style.color
= "red";
element.style.backgroundColor
= "yellow";
Or better, toggle CSS classes:
element.classList.add('active');
element.classList.remove('hidden');
const
div = document.createElement('div');
div.textContent = "Hello!";
document.body.appendChild(div);
element.remove();
// Modern way
// OR
element.parentNode.removeChild(element);
// Older method
const
button = document.querySelector('button');
button.addEventListener('click',
function() {
alert('Button clicked!');
});
Please log in to access this content. You will be redirected to the login page shortly.
LoginReady to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Comments(0)