- Select DOM elements with modern selectors
- Modify element content, attributes, and styles
- Create and remove elements dynamically
- Use array methods to transform data
- Combine DOM manipulation with array operations
BMC201 - Web Technology
2026-02-23
Lecture 17
DOM Manipulation & Array Methods
Week 5 | Unit II: DOM Manipulation
BMC201 - Web Technology
Mr. Prashant Kumar Nag, Assistant Professor
Learning Objectives
What is the DOM?
The Document Object Model is a tree-like representation of HTML.
Selecting Elements
document.getElementById('header');
document.querySelector('.navbar');
document.querySelectorAll('p');
document.getElementsByClassName('item');querySelector returns first matchquerySelectorAll returns all matches (NodeList)Reading and Modifying Content
const para = document.querySelector('p');
console.log(para.textContent); // text only
console.log(para.innerHTML); // HTML markup
para.innerHTML = "<strong>Updated!</strong>";textContent: plain textinnerHTML: HTML tags includedModifying Attributes
const img = document.querySelector('img');
img.setAttribute('src', 'photo.jpg');
img.alt = 'Profile picture';
console.log(img.getAttribute('src'));Attributes control element behavior and display.
Modifying Styles
const box = document.querySelector('.box');
box.style.color = 'blue';
box.style.backgroundColor = 'lightgray';
box.style.fontSize = '18px';CSS property names become camelCase in JavaScript.
Working with Classes
const btn = document.querySelector('button');
btn.classList.add('active');
btn.classList.remove('disabled');
btn.classList.toggle('highlight');
console.log(btn.classList.contains('active'));classList is cleaner than manipulating className directly.
Creating New Elements
const newDiv = document.createElement('div');
newDiv.textContent = 'Hello from JS!';
newDiv.classList.add('message');
const parent = document.querySelector('#container');
parent.appendChild(newDiv);Dynamically build UI from JavaScript.
Removing Elements
const item = document.querySelector('.old-item');
item.remove();
// OR using parent
parent.removeChild(item);Use .remove() for simpler code.
Array Method: map()
const nums = [1, 2, 3, 4];
const doubled = nums.map(x => x * 2);
console.log(doubled); // [2, 4, 6, 8]map() transforms each element and returns a new array.
Array Method: filter()
const numbers = [5, 12, 8, 130, 44];
const large = numbers.filter(n => n > 10);
console.log(large); // [12, 130, 44]filter() selects elements that pass a test.
Array Method: reduce()
const values = [10, 20, 30];
const sum = values.reduce((acc, val) => acc + val, 0);
console.log(sum); // 60reduce() combines all elements into a single value.
Array Methods: find() & includes()
Combining DOM & Arrays
Practice Task
Given an array of product prices, create a <ul> with one <li> per product showing: “Price: ₹X”
Use map() or forEach() to build the list dynamically.
Questions?
Next: Lecture 18 - Form Validation