Learning Implementation
🧱 Real-World DOM Use-Cases with Array Methods
🔁 forEach() in the DOM
✅ Best For:
Attaching event listeners to multiple elements
Iterating over NodeLists (e.g.,
.querySelectorAll())Showing/hiding items
Adding/removing classes
javascriptCopyEditconst buttons = document.querySelectorAll(".accordion-button");
buttons.forEach((btn, i) => {
btn.addEventListener("click", () => {
console.log(`Button ${i} clicked`);
btn.classList.toggle("active");
});
});
🧬 map() in the DOM
✅ Best For:
Generating HTML dynamically from data
Returning transformed elements (can be used with
.innerHTML)
javascriptCopyEditconst users = [
{ name: "Alice", age: 22 },
{ name: "Bob", age: 25 },
];
const container = document.querySelector("#user-list");
container.innerHTML = users
.map(user => `<div class="user">${user.name} - ${user.age}</div>`)
.join("");
🔍 filter() in the DOM
✅ Best For:
Showing only certain elements (e.g., filtering search results)
Creating dynamic UIs (e.g., category filters)
javascriptCopyEditconst items = [
{ name: "Laptop", type: "electronics" },
{ name: "T-shirt", type: "clothing" },
{ name: "Phone", type: "electronics" },
];
const electronics = items.filter(item => item.type === "electronics");
document.querySelector("#items").innerHTML = electronics
.map(item => `<li>${item.name}</li>`)
.join("");
➕ reduce() in the DOM
✅ Best For:
Calculating totals (e.g., shopping cart totals)
Grouping data for display
javascriptCopyEditconst cart = [
{ name: "Phone", price: 400 },
{ name: "Charger", price: 40 },
];
const total = cart.reduce((sum, item) => sum + item.price, 0);
document.querySelector("#total").textContent = `Total: $${total}`;
🔍 find() and findIndex() in the DOM
✅ Best For:
Selecting a single element from a list
Handling "Edit" actions for dynamic content
javascriptCopyEditconst users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
];
const userToEdit = users.find(user => user.id === 2);
document.querySelector("#edit-name").value = userToEdit.name;
✅ some() and every() in the DOM
✅ Best For:
Form validation (e.g., check if all fields are filled)
Checking conditions across UI components
javascriptCopyEditconst inputs = document.querySelectorAll("input");
const allFilled = [...inputs].every(input => input.value.trim() !== "");
if (!allFilled) {
alert("Please fill in all fields!");
}
🪜 flatMap() in the DOM
✅ Best For:
Rendering deeply nested data structures into flat UI
Combining and flattening results (e.g., tags, categories)
javascriptCopyEditconst categories = [
{ name: "Fruits", items: ["Apple", "Banana"] },
{ name: "Veggies", items: ["Carrot", "Spinach"] },
];
const allItems = categories.flatMap(cat => cat.items);
document.querySelector("#all-items").innerHTML = allItems
.map(item => `<li>${item}</li>`)
.join("");
💡 Bonus: Real Example — Dynamic Accordion
Here’s how multiple methods might work together:
javascriptCopyEditconst faqs = [
{ question: "What is HTML?", answer: "HTML is markup language." },
{ question: "What is JS?", answer: "JS is a scripting language." }
];
const container = document.querySelector("#faq");
container.innerHTML = faqs
.map((faq, index) => `
<div class="faq-item">
<button class="faq-question" data-index="${index}">${faq.question}</button>
<div class="faq-answer hidden">${faq.answer}</div>
</div>
`).join("");
document.querySelectorAll(".faq-question").forEach(btn => {
btn.addEventListener("click", () => {
const answer = btn.nextElementSibling;
answer.classList.toggle("hidden");
});
});
🚀 Summary Table for DOM Use
| Method | DOM Use-case Examples |
forEach | Event listeners, class toggling |
map | Generating innerHTML from data |
filter | Showing filtered content (e.g., search, categories) |
reduce | Totals, counting, grouping |
find | Find data to populate forms or modals |
some | Check if any input is invalid |
every | Confirm all form fields are valid |
flatMap | Flatten nested arrays for rendering |
About the author
💻 Software Developer | 🚀 Building next-gen digital platforms 🔭 Currently working on a fan-influencer interaction startup 💡 Passionate about scalable systems, DSA, system design & product thinking 📚 Electrical Engineering @NIT JSR | 2nd Year ✨ Learning in public | Sharing my journey in tech & startups
Comments
Join the discussionNo comments yet. Be the first to comment.