Skip to main content

DOM Manipulation

Level: Beginner

ℹ️ What You'll Learn
  • What DOM Manipulation means in JavaScript
  • Why this topic matters in real web pages
  • How to use it with School Management System examples
  • Common beginner mistakes to avoid
  • How to explain this topic in interviews

Why This Matters

DOM Manipulation is part of the practical frontend foundation. You will use it when building forms, tables, dashboards, reports, and API-connected screens for ASP.NET Core or full-stack projects.

Update HTML elements dynamically with API data.

The Problem

Beginners often copy JavaScript code without understanding what each line does. In a real School Management System, that leads to pages that are hard to maintain, hard to debug, or confusing for users. This lesson focuses on understanding the pattern first, then applying it in small practical examples.

Select Elements

// By ID
const element = document.getElementById('studentTable');

// By class
const elements = document.querySelectorAll('.student-row');

// By tag
const inputs = document.getElementsByTagName('input');

// By CSS selector (most flexible)
const button = document.querySelector('.delete-btn');
const cells = document.querySelectorAll('tr td');

Update Element Content

const element = document.getElementById('message');

// Set text
element.textContent = 'Student list loaded';

// Set HTML
element.innerHTML = '<p>Welcome <strong>Ravi Kumar</strong></p>';

// Get content
const text = element.textContent;
const html = element.innerHTML;

Create and Add Elements

// Create new element
const newRow = document.createElement('tr');
newRow.innerHTML = `
<td>101</td>
<td>Ravi Kumar</td>
<td>ravi@example.com</td>
<td>Active</td>
`;

// Add to table
const tableBody = document.querySelector('tbody');
tableBody.appendChild(newRow);

Populate Table from API

async function loadStudents() {
try {
// Fetch data
const response = await fetch('/api/students');
const students = await response.json();

// Get table body
const tableBody = document.querySelector('#studentTable tbody');
tableBody.innerHTML = ''; // Clear existing rows

// Add rows for each student
students.forEach(student => {
const row = document.createElement('tr');
row.dataset.studentId = student.id;
row.innerHTML = `
<td>${student.rollNumber}</td>
<td>${student.name}</td>
<td>${student.email}</td>
<td>${student.className}</td>
<td>${student.status}</td>
<td>
<button class="edit-btn">Edit</button>
<button class="delete-btn">Delete</button>
</td>
`;
tableBody.appendChild(row);
});

// Update count
document.getElementById('studentCount').textContent = students.length;

} catch (error) {
console.error('Error loading students:', error);
document.getElementById('error').textContent = 'Failed to load students';
}
}

// Call on page load
loadStudents();

Manipulate Attributes

const element = document.getElementById('myButton');

// Set attribute
element.setAttribute('disabled', 'true');
element.dataset.action = 'submit'; // data-action

// Get attribute
const value = element.getAttribute('data-student-id');
const action = element.dataset.action;

// Check if has attribute
if (element.hasAttribute('disabled')) {
console.log('Button is disabled');
}

// Remove attribute
element.removeAttribute('disabled');

Style Elements

const element = document.getElementById('status');

// Set inline styles
element.style.color = 'green';
element.style.fontWeight = 'bold';
element.style.backgroundColor = '#f0f0f0';

// Add CSS class
element.classList.add('status-active');

// Remove CSS class
element.classList.remove('status-inactive');

// Toggle CSS class
element.classList.toggle('highlight');

// Check if has class
if (element.classList.contains('error')) {
console.log('Element has error class');
}

Display Student Details

async function showStudentDetails(studentId) {
try {
const response = await fetch(`/api/students/${studentId}`);
const student = await response.json();

// Update HTML
document.getElementById('studentName').textContent = student.name;
document.getElementById('studentEmail').textContent = student.email;
document.getElementById('studentClass').textContent = student.className;
document.getElementById('studentStatus').textContent = student.status;

// Update status color
const statusEl = document.getElementById('studentStatus');
if (student.status === 'Active') {
statusEl.style.color = 'green';
} else {
statusEl.style.color = 'red';
}

// Show details container
document.getElementById('detailsContainer').style.display = 'block';

} catch (error) {
console.error('Error:', error);
}
}

Real SMS Example: Dynamic Student List

// When page loads
document.addEventListener('DOMContentLoaded', async () => {
// Load students
await loadStudents();

// Add event listeners for action buttons
document.addEventListener('click', async (event) => {
if (event.target.classList.contains('edit-btn')) {
const row = event.target.closest('tr');
const studentId = row.dataset.studentId;
editStudent(studentId);
}

if (event.target.classList.contains('delete-btn')) {
const row = event.target.closest('tr');
const studentId = row.dataset.studentId;
const name = row.querySelector('td:nth-child(2)').textContent;

if (confirm(`Delete ${name}?`)) {
deleteStudent(studentId);
}
}
});
});

async function loadStudents() {
try {
const response = await fetch('/api/students');
const students = await response.json();

const tableBody = document.querySelector('tbody');
tableBody.innerHTML = '';

students.forEach(student => {
const row = document.createElement('tr');
row.dataset.studentId = student.id;
row.innerHTML = `
<td>${student.rollNumber}</td>
<td>${student.name}</td>
<td>${student.className}</td>
<td>
<span class="${student.status === 'Active' ? 'status-active' : 'status-inactive'}">
${student.status}
</span>
</td>
<td>
<button class="edit-btn">Edit</button>
<button class="delete-btn">Delete</button>
</td>
`;
tableBody.appendChild(row);
});

} catch (error) {
console.error('Error:', error);
}
}

async function deleteStudent(studentId) {
try {
const response = await fetch(`/api/students/${studentId}`, {
method: 'DELETE'
});

if (response.ok) {
alert('Student deleted');
loadStudents(); // Refresh list
}
} catch (error) {
console.error('Error:', error);
}
}

Key Takeaways

  • Use querySelector for flexible element selection
  • innerHTML for complex content
  • Create elements with createElement and appendChild
  • Use dataset to access data attributes
  • Add/remove classes for styling
  • Next: Event listeners
💡 Backend Developer Tip

Use innerHTML carefully - it can execute scripts. For user input, use textContent instead.

⚠️ DOM Mistakes
  1. Using innerHTML with user input — XSS vulnerability
  2. Forgetting to clear old data — Duplicates appear
  3. Using same ID multiple times — querySelector returns first only
  4. Not waiting for DOM ready — Elements not loaded yet
🤖Use AI to Learn Faster

Use ChatGPT, Claude, or Copilot to go deeper on DOM Manipulation. Try these prompts:

  • "When use innerHTML vs textContent?"
  • "How do you dynamically add table rows?"
  • "What are data attributes used for?"
  • "Quiz me on DOM manipulation"

💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.

Quick Definitions

  • DOM Manipulation - The main concept explained in this lesson.
  • Selector/element/data - The page item or value you work with while applying this concept.
  • Real project usage - How this appears in forms, tables, dashboards, or API-connected pages.

Common Mistakes

  • Copying code without understanding what each line does
  • Forgetting to test with real School Management System data
  • Ignoring mobile screens and accessibility
  • Mixing structure, styling, and behavior in a confusing way
  • Not checking browser DevTools when something does not work

Practice Task

Create a small School Management System example using DOM Manipulation. Keep it simple first, then improve it step by step.

Suggested practice:

  1. Build a small student-related screen or component.
  2. Use clear names for elements, classes, variables, or functions.
  3. Test one success case and one failure case.
  4. Explain the code in your own words.
  5. Rebuild it once without looking at the article.

Quick Revision

QuestionAnswer
What is the main idea?Understand and apply DOM Manipulation in a real page.
Where is it used?Student forms, reports, dashboards, and admin screens.
What should beginners focus on?Clear structure, small examples, and repeated practice.
What is the best debugging habit?Inspect the page in browser DevTools and test one change at a time.
🎯 How would you explain DOM Manipulation in an interview?

DOM Manipulation is a practical JavaScript concept used to build clear, maintainable web pages. I would explain what problem it solves, show a small example, and mention one common mistake beginners should avoid.

🎯 Where is this used in a real project?

It is used in screens like student registration, attendance entry, marks reports, dashboards, and API-connected admin pages.

Next Article

Loops ->

nexcoding.in