MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
querySelectorAll & forEach0%
Study Materials
JavaScript for IntermediateProgress 0%
1.1Block Scope with let & const1.2Template Literals1.3Destructuring Arrays and Objects1.4Default Parameters1.5Enhanced Object Literals
3.1querySelectorAll & forEach3.2Traversing DOM Nodes3.3Dynamic Element Creation & Removal3.4Styling with classList
HomeTutorialsJavaScript for IntermediatequerySelectorAll & forEach
Traversing DOM Nodes

querySelectorAll & forEach

Beginner12 min read•Updated: 2026-09-15•By Er. Sumit Kumar (MSK Institute)
Study Materials

Selecting and manipulating collections of DOM nodes is a cornerstone of client-side web development. While single-element selectors like getElementById() or querySelector() return either an Element or null, document.querySelectorAll() matches all DOM elements satisfying a standard CSS selector and returns a static NodeList.


1. querySelector vs. querySelectorAll

Understanding the return types and behavioral differences is vital:

FeaturequerySelector()querySelectorAll()getElementsByClassName()
Return TypeSingle Element or nullStatic NodeListLive HTMLCollection
Selector SyntaxAny CSS selectorAny CSS selectorClass name string only
Iteration SupportN/A (Single node)Native .forEach()Requires conversion to Array
DOM Mutation EffectNo effect on variableSnapshot (Static)Live updates with DOM changes
1// Selecting single element
2const submitBtn = document.querySelector('#btn-submit');
3 
4// Selecting all matching elements (Static NodeList)
5const featureCards = document.querySelectorAll('.card.feature');
6console.log(`Found ${featureCards.length} feature cards.`);

2. Iterating with NodeList.prototype.forEach

Modern browsers support .forEach() directly on NodeList instances, enabling clean functional iteration without manual for loops.

1const navLinks = document.querySelectorAll('nav a.nav-item');
2 
3navLinks.forEach((link, index) => {
4 // Check if link is active
5 if (link.getAttribute('href') === window.location.pathname) {
6 link.classList.add('active');
7 }
8
9 // Attach telemetry or custom interaction
10 link.addEventListener('click', (event) => {
11 console.log(`User clicked nav item #${index + 1}: ${link.textContent}`);
12 });
13});

3. NodeList vs. HTMLCollection vs. Array

A NodeList is not an Array. While modern NodeList has .forEach(), it lacks array transformation methods like .map(), .filter(), .reduce(), or .some().

Converting NodeList to an Array

To leverage array transformations, convert the NodeList using the spread operator or Array.from():

1const priceBadges = document.querySelectorAll('.badge-price');
2 
3// Option A: Spread operator (Recommended)
4const priceElements = [...priceBadges];
5 
6// Option B: Array.from() with mapping callback
7const prices = Array.from(priceBadges, (el) => parseFloat(el.textContent.replace('$', '')));
8 
9// Now you can filter and reduce!
10const affordablePrices = prices.filter(price => price < 50.00);
11const totalPrice = prices.reduce((sum, price) => sum + price, 0);
12 
13console.log('Prices under $50:', affordablePrices);
14console.log('Total Cart Value:', totalPrice.toFixed(2));

4. Static vs. Live Collections

querySelectorAll() returns a static snapshot. Changes to the DOM after the query will not be reflected in the existing NodeList:

1const container = document.querySelector('#container');
2const staticList = document.querySelectorAll('.item'); // e.g., 3 items
3const liveList = document.getElementsByClassName('item'); // 3 items
4 
5// Add a new element dynamically
6const newItem = document.createElement('div');
7newItem.className = 'item';
8container.appendChild(newItem);
9 
10console.log(staticList.length); // Still 3! (Static snapshot)
11console.log(liveList.length); // 4! (Live collection updated automatically)
Pro Tip
Static collections are generally faster and safer because iterating over a live collection while mutating the DOM can cause infinite loops or skipped indices.

5. Practical Example: Tab Controller

1function initTabs() {
2 const tabButtons = document.querySelectorAll('[data-tab-target]');
3 const tabPanes = document.querySelectorAll('.tab-pane');
4 
5 tabButtons.forEach(button => {
6 button.addEventListener('click', () => {
7 const targetSelector = button.getAttribute('data-tab-target');
8 const targetPane = document.querySelector(targetSelector);
9 
10 // Deactivate all buttons & panes
11 tabButtons.forEach(btn => btn.classList.remove('active'));
12 tabPanes.forEach(pane => pane.classList.remove('show'));
13 
14 // Activate current
15 button.classList.add('active');
16 if (targetPane) {
17 targetPane.classList.add('show');
18 }
19 });
20 });
21}

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What does document.querySelectorAll() return when matching multiple elements?
Question 2
How can you convert a NodeList into a true JavaScript Array to use array methods like .filter()?
Question 3
How does a static NodeList behave when a new matching element is appended to the DOM after querying?
Question 4
Which method is natively available on modern NodeList instances without converting to an Array?
Question 5
What is returned by document.querySelectorAll('.non-existent-class') if no elements match?
Next Lesson

Traversing DOM Nodes

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Immediately Invoked Functions (IIFE)Traversing DOM Nodes

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Intermediate with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext