Module 2: DOM Selection Methods - Study Notes
📚 Overview
Duration: Week 2
Prerequisites: Module 1 (DOM Fundamentals)
Goal: Master finding and selecting elements in the DOM - your essential toolkit for web
development.
🎯 Learning Objectives
By the end of this module, you will be able to:
✅ Use 7 different methods to find DOM elements
✅ Choose the right selection method for each situation
✅ Navigate between related elements (parent, child, sibling)
✅ Understand the difference between NodeList and HTMLCollection
✅ Write efficient CSS selectors in JavaScript
📖 Section 2.1: Traditional Selection Methods
Think of These as Your "Classic Tools" 🛠️
These are the original DOM selection methods - reliable and straightforward.
1. getElementById()
What it does: Finds ONE element by its ID
Returns: Single element OR null (if not found)
Speed: ⚡ Very fast (IDs are unique)
javascript
// HTML: <div id="header">Welcome</div>
const header = [Link]('header');
[Link](header); // Returns the div element
Key Points:
Only finds ONE element (IDs should be unique)
Returns null if ID doesn't exist
Don't include the # symbol
Case-sensitive
2. getElementsByClassName()
What it does: Finds ALL elements with a specific CSS class
Returns: HTMLCollection (live list)
Speed: ⚡ Fast
javascript
// HTML: <p class="highlight">Text 1</p><p class="highlight">Text 2</p>
const highlights = [Link]('highlight');
[Link]([Link]); // 2
[Link](highlights[0]); // First paragraph
Key Points:
Returns a LIVE collection (updates automatically)
Don't include the . symbol
Can specify multiple classes: 'class1 class2'
Always returns a collection, even if only 1 element found
3. getElementsByTagName()
What it does: Finds ALL elements of a specific HTML tag
Returns: HTMLCollection (live list)
Speed: ⚡ Fast
javascript
// Find all paragraphs
const paragraphs = [Link]('p');
[Link]([Link]); // Number of <p> elements
// Find all elements
const allElements = [Link]('*');
Key Points:
Case-insensitive ('P' or 'p' both work)
Use '*' to get ALL elements
Returns live collection
4. getElementsByName()
What it does: Finds ALL elements with specific name attribute
Returns: NodeList
Speed: ⚡ Fast
Common use: Form elements
javascript
// HTML: <input name="email" type="text">
const emailInputs = [Link]('email');
[Link](emailInputs[0].value); // Get input value
Key Points:
Mainly used for form elements
Less commonly used than other methods
Returns NodeList (not HTMLCollection)
Quick Comparison Table:
Method Finds Returns Live? Symbol?
getElementById() 1 element by ID Element/null No No #
getElementsByClassName() Multiple by class HTMLCollection Yes No .
getElementsByTagName() Multiple by tag HTMLCollection Yes None
getElementsByName() Multiple by name NodeList No None
📖 Section 2.2: Modern Query Methods
Think of These as Your "Swiss Army Knife" 🔪
More powerful and flexible - use CSS selector syntax!
1. querySelector()
What it does: Finds the FIRST element matching a CSS selector
Returns: Single element OR null
Speed: 🐌 Slower but more flexible
javascript
// By ID
const header = [Link]('#header');
// By class
const firstHighlight = [Link]('.highlight');
// By tag
const firstParagraph = [Link]('p');
// Complex selectors
const nestedSpan = [Link]('[Link] span');
const firstListItem = [Link]('ul li:first-child');
2. querySelectorAll()
What it does: Finds ALL elements matching a CSS selector
Returns: NodeList (static - doesn't auto-update)
Speed: 🐌 Slower but very powerful
javascript
// All elements with class 'highlight'
const allHighlights = [Link]('.highlight');
// All paragraphs inside divs
const nestedP = [Link]('div p');
// Complex selections
const evenListItems = [Link]('li:nth-child(even)');
CSS Selector Syntax in JavaScript
Basic Selectors:
javascript
[Link]('p') // First <p> tag
[Link]('#myId') // Element with id="myId"
[Link]('.myClass') // First element with class="myClass"
[Link]('*') // First element (any tag)
Combination Selectors:
javascript
[Link]('div p') // First <p> inside any <div>
[Link]('div > p') // First <p> that's direct child of <div>
[Link]('h1 + p') // First <p> immediately after <h1>
[Link]('[Link]') // First <div> with class="highlight"
Attribute Selectors:
javascript
[Link]('[type="text"]') // Element with type="text"
[Link]('input[required]') // Input with required attribute
[Link]('a[href^="https"]') // Link starting with "https"
Pseudo-class Selectors:
javascript
[Link]('li:first-child') // First <li> in its parent
[Link]('li:last-child') // Last <li> in its parent
[Link]('tr:nth-child(odd)') // Odd table rows
[Link]('input:focus') // Currently focused input
Performance Considerations
Fast Methods (Use When Possible):
getElementById() - Fastest
getElementsByClassName() - Very fast
getElementsByTagName() - Very fast
Slower Methods (More Flexible):
querySelector() - Slower but powerful
querySelectorAll() - Slowest but most flexible
Performance Tip: If you just need an ID or class, use the traditional methods. Use query
methods for complex selections.
📖 Section 2.3: Node Relationships
Think of the DOM as a Family Tree 👨👩👧👦
Elements have parents, children, and siblings - just like a family!
Parent-Child Relationships
parentNode
What it does: Gets the parent element
Returns: Parent element OR null (if at root)
javascript
// HTML: <div><p id="child">Text</p></div>
const child = [Link]('child');
const parent = [Link];
[Link]([Link]); // "DIV"
childNodes
What it does: Gets ALL child nodes (including text and whitespace!)
Returns: NodeList (includes text nodes)
javascript
// HTML: <div><p>Para 1</p><p>Para 2</p></div>
const div = [Link]('div');
[Link]([Link]); // Might be 5 (includes whitespace text nodes!)
⚠️ Important: childNodes includes text nodes (even whitespace). This can be confusing!
children (Better Alternative)
What it does: Gets only ELEMENT children (ignores text nodes)
Returns: HTMLCollection (elements only)
javascript
const div = [Link]('div');
[Link]([Link]); // 2 (just the <p> elements)
[Link]([Link][0]); // First <p> element
Sibling Navigation
nextSibling / previousSibling
What they do: Get next/previous node (including text!)
Problem: Often returns text nodes (whitespace)
javascript
// Often returns text nodes - not what you want!
const next = [Link]; // Might be whitespace
nextElementSibling / previousElementSibling (Better!)
What they do: Get next/previous ELEMENT (skips text)
Returns: Element OR null
javascript
// HTML: <div><p>First</p><p>Second</p><p>Third</p></div>
const secondP = [Link]('p')[1];
const firstP = [Link];
const thirdP = [Link];
Element-Specific Navigation (Recommended)
These are cleaner because they only deal with elements, not text nodes:
javascript
// Better ways to navigate:
[Link] // Parent element (not text)
[Link] // Child elements (not text)
[Link] // First child element
[Link] // Last child element
[Link] // Next sibling element
[Link] // Previous sibling element
Navigation Cheat Sheet:
Property Gets Includes Text? Recommended?
parentNode Parent Yes ✅ Safe
childNodes All children Yes ❌ Confusing
children Child elements No ✅ Better
nextSibling Next node Yes ❌ Confusing
nextElementSibling Next element No ✅ Better
🔄 NodeList vs HTMLCollection
Understanding the Difference
HTMLCollection (Live)
javascript
const divs = [Link]('div');
[Link]([Link]); // Let's say 5
// Add a new div to the page
[Link]([Link]('div'));
[Link]([Link]); // Now 6! (automatically updated)
NodeList (Usually Static)
javascript
const paragraphs = [Link]('p');
[Link]([Link]); // Let's say 3
// Add a new paragraph to the page
[Link]([Link]('p'));
[Link]([Link]); // Still 3! (not updated)
Key Differences:
Feature HTMLCollection NodeList
Live Updates ✅ Yes ❌ Usually No
Array Methods ❌ No ✅ Some (forEach)
Returned by getElementsBy... querySelectorAll, childNodes
Converting to Real Arrays:
javascript
// Convert HTMLCollection or NodeList to array
const elements = [Link]([Link]('item'));
const elements2 = [...[Link]('.item')]; // Spread operator
🛠️ Practical Exercises
Exercise 1: Form Validator
Goal: Practice different selection methods
HTML Setup:
html
<form id="signup-form">
<input type="text" id="username" name="username" class="required"
placeholder="Username">
<input type="email" id="email" name="email" class="required" placeholder="Email">
<input type="password" id="password" name="password" class="required"
placeholder="Password">
<button type="submit">Sign Up</button>
</form>
<div class="error-messages"></div>
Practice Tasks:
javascript
// Task 1: Get form by ID
const form = [Link]('signup-form');
// Task 2: Get all required fields by class
const requiredFields = [Link]('required');
// Task 3: Get specific input by name
const emailField = [Link]('email')[0];
// Task 4: Use querySelector for complex selection
const submitButton = [Link]('form button[type="submit"]');
// Task 5: Get all inputs using querySelectorAll
const allInputs = [Link]('input');
Exercise 2: Navigation Highlighter
Goal: Practice querySelector and navigation
HTML Setup:
html
<nav>
<ul>
<li><a href="#home" class="nav-link">Home</a></li>
<li><a href="#about" class="nav-link">About</a></li>
<li><a href="#contact" class="nav-link active">Contact</a></li>
</ul>
</nav>
Practice Tasks:
javascript
// Task 1: Find current active link
const activeLink = [Link]('.[Link]');
// Task 2: Find its parent <li>
const activeLi = [Link];
// Task 3: Find all navigation links
const allNavLinks = [Link]('.nav-link');
// Task 4: Find the next navigation item
const nextLi = [Link];
// Task 5: Complex selector - first nav link
const firstNavLink = [Link]('nav ul li:first-child a');
Exercise 3: DOM Tree Walker
Goal: Practice node relationships
Practice Code:
javascript
function exploreElement(element) {
[Link]('Tag:', [Link]);
[Link]('Parent:', [Link]?.tagName || 'None');
[Link]('Children:', [Link]);
[Link]('Next sibling:', [Link]?.tagName || 'None');
// Try on different elements
const body = [Link];
const firstDiv = [Link]('div');
const lastParagraph = [Link]('p:last-of-type');
}
🧠 Memory Aids & Tips
Selection Method Memory Device: "QICT"
QuerySelector (modern, flexible)
Id (getElementById - fastest)
Class (getElementsByClassName)
Tag (getElementsByTagName)
CSS Selector Quick Reference:
javascript
'#id' // ID selector
'.class' // Class selector
'tag' // Tag selector
'parent child' // Descendant
'parent > child' // Direct child
'element:first-child' // Pseudo-class
'[attribute]' // Has attribute
'[attr="value"]' // Attribute equals
Navigation Memory Device: "PCN"
Parent (parentElement)
Children (children)
Next/Previous (nextElementSibling)
❓ Self-Check Questions
Basic Understanding:
1. What's the difference between querySelector() and getElementById()?
2. Why might getElementsByClassName() be faster than
querySelectorAll('.classname')?
3. What's the difference between childNodes and children?
Practical Application:
4. How would you select all paragraphs inside divs with class "content"?
5. How do you get the parent of an element?
6. What's returned by getElementsByTagName() if no elements are found?
Advanced Concepts:
7. What's the difference between HTMLCollection and NodeList?
8. Why is nextElementSibling usually better than nextSibling?
9. When would you use querySelector() vs getElementById()?
🎯 Assessment Preparation
Coding Challenges You Should Be Able to Do:
Select elements using all 7 methods
Write complex CSS selectors in querySelector
Navigate between related elements
Convert HTMLCollection/NodeList to arrays
Choose the most efficient selection method for each task
Performance Comparison Exercise Prep:
javascript
// Time different selection methods
[Link]('getElementById');
[Link]('test');
[Link]('getElementById');
[Link]('querySelector');
[Link]('#test');
[Link]('querySelector');
🚀 Common Patterns You'll Use
The "Find and Loop" Pattern:
javascript
const buttons = [Link]('button');
[Link](button => {
// Do something with each button
[Link]([Link]);
});
The "Check if Exists" Pattern:
javascript
const element = [Link]('.optional-element');
if (element) {
// Element exists, safe to use
[Link] = 'red';
}
The "Family Navigation" Pattern:
javascript
const clickedButton = [Link];
const container = [Link];
const siblings = [Link];
💡 Pro Tips
1. Start with simple selectors - Only use complex ones when needed
2. Prefer Element methods over Node methods (avoids text node confusion)
3. Cache your selections - Don't re-query the same elements
4. Use [Link]() to see what your selectors return
5. Practice CSS selectors separately - they're used everywhere in web dev
📝 Next Steps
After mastering Module 2, you'll be ready for:
Module 3: DOM Manipulation (changing what you've selected)
Module 4: Event Handling (making selections interactive)
Foundation you've built:
Can find any element in any webpage
Understand DOM relationships
Know when to use which selection method
Ready to modify what you've found
Remember: Selection is the foundation of all DOM work. Master these methods and you
can control any webpage!