LearnFrenzy
Sign in Take a free test
JS

JavaScript Programming · Topic 23 of 25

DOM Manipulation Questions and Concepts

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

DOM Manipulation · Study material

The DOM (Document Object Model) is the live tree of objects the browser builds from your HTML. JavaScript reads and changes that tree – text, attributes, classes, styles, whole elements – and listens to events such as clicks and key presses; the browser redraws the page to match. DOM skills are tested in every front-end interview and machine-coding round: selecting elements, textContent vs innerHTML (and XSS), live vs static collections, attributes vs properties, bubbling and capturing, and event delegation. Each example below shows the HTML page and the script that runs on it, with the output it really produced. Then test yourself with 60 practice questions – 15 MCQs, 20 predict-the-output puzzles, 15 debugging questions and 10 coding problems – each run inside its page.

Selecting elements

getElementById finds one element by id; querySelector returns the first element matching any CSS selector, and querySelectorAll returns all of them as a static NodeList. Both return null / an empty list when nothing matches – always check before using the result.

HTML

<h1 id="title">LearnFrenzy</h1>
<ul id="courses">
  <li class="course">JavaScript</li>
  <li class="course free">Python</li>
  <li class="course">SQL</li>
</ul>

JavaScript

const title = document.getElementById("title");             // one element by id
const firstFree = document.querySelector(".course.free");    // first match of a CSS selector
const all = document.querySelectorAll("#courses .course");   // every match (a static NodeList)
const missing = document.querySelector(".premium");          // no match → null

console.log(title.textContent);
console.log(firstFree.textContent);
console.log(all.length, [...all].map((li) => li.textContent).join(", "));
console.log(missing);

Output

LearnFrenzy
Python
3 JavaScript, Python, SQL
null

Changing content, attributes, classes and styles

textContent sets plain text; innerHTML parses HTML. setAttribute/getAttribute work with HTML attributes, classList adds, removes and toggles classes, dataset reads and writes data-* attributes (data-course-id → dataset.courseId), and style sets inline styles in camelCase.

HTML

<div id="card" class="card" data-course-id="js101">
  <h2>Old title</h2>
  <a href="/old">Open</a>
</div>

JavaScript

const card = document.querySelector("#card");
card.querySelector("h2").textContent = "Event Loop – Practice";   // text, never parsed as HTML
card.querySelector("a").setAttribute("href", "/javascript/event-loop");
card.classList.add("highlight");
card.classList.remove("card");
card.classList.toggle("new");                                      // adds it (it was missing)
card.dataset.level = "pro";                                        // writes data-level="pro"
card.style.borderColor = "orange";

console.log(card.querySelector("h2").textContent);
console.log(card.querySelector("a").getAttribute("href"));
console.log(card.className);
console.log(card.dataset.courseId, card.dataset.level);
console.log(card.getAttribute("style"));

Output

Event Loop – Practice
/javascript/event-loop
highlight new
js101 pro
border-color: orange;

Creating, inserting and removing elements

Create with document.createElement, insert with append, prepend, before, after or insertAdjacentHTML, replace with replaceWith/replaceChildren, and remove with remove(). Inserting an element that is already on the page moves it.

HTML

<ul id="list"><li>Second</li></ul>

JavaScript

const list = document.getElementById("list");

const first = document.createElement("li");
first.textContent = "First";
list.prepend(first);                         // at the start

const last = document.createElement("li");
last.textContent = "Last";
list.append(last);                           // at the end

list.children[1].after(Object.assign(document.createElement("li"), { textContent: "Third" }));
list.insertAdjacentHTML("beforeend", "<li>Temporary</li>");
list.lastElementChild.remove();              // remove the temporary item

console.log([...list.children].map((li) => li.textContent).join(" → "));
console.log(list.outerHTML);

Output

First → Second → Third → Last
<ul id="list"><li>First</li><li>Second</li><li>Third</li><li>Last</li></ul>

Events: bubbling and capturing

addEventListener(type, handler) attaches a listener. An event travels down from the window to the target (capturing phase), then back up (bubbling phase); listeners run in the bubbling phase unless you pass true or { capture: true }. event.target is the element that was clicked; event.currentTarget is the element whose listener is running.

HTML

<section id="page">
  <div id="box"><button id="buy">Buy</button></div>
</section>

JavaScript

const log = [];
const page = document.getElementById("page");
const box = document.getElementById("box");
const buy = document.getElementById("buy");

page.addEventListener("click", () => log.push("page (capture)"), true);   // capturing phase: top-down
page.addEventListener("click", () => log.push("page (bubble)"));
box.addEventListener("click", (e) => log.push(`box – target: ${e.target.id}, currentTarget: ${e.currentTarget.id}`));
buy.addEventListener("click", () => log.push("button"));

buy.click();                                  // a real click event, dispatched synchronously
console.log(log.join("\n"));

Output

page (capture)
button
box – target: buy, currentTarget: box
page (bubble)

Event delegation

Because events bubble, one listener on a parent can handle clicks on all of its children – including children added later. Use event.target.closest(selector) to find the element you care about.

HTML

<ul id="todos">
  <li data-id="1">Revise closures <button class="del">✕</button></li>
  <li data-id="2">Practise DOM <button class="del">✕</button></li>
</ul>

JavaScript

const todos = document.getElementById("todos");

// ONE listener on the parent handles every button – even for items added later
todos.addEventListener("click", (e) => {
  const btn = e.target.closest(".del");
  if (!btn) return;                                 // the click was not on a delete button
  const item = btn.closest("li");
  console.log(`deleting #${item.dataset.id}`);
  item.remove();
});

todos.insertAdjacentHTML("beforeend", '<li data-id="3">Mock test <button class="del">✕</button></li>');
todos.querySelector('[data-id="3"] .del').click();  // works for the new item too
todos.querySelector('[data-id="1"] .del').click();
console.log("left:", todos.children.length);

Output

deleting #3
deleting #1
left: 1

Preventing the default action

event.preventDefault() stops the browser's built-in action (submitting a form, following a link, ticking a checkbox). event.stopPropagation() is different: it stops the event from reaching other elements.

HTML

<form id="signup">
  <input id="email" name="email" value="asha@">
  <button>Sign up</button>
</form>

JavaScript

const form = document.getElementById("signup");
form.addEventListener("submit", (e) => {
  const email = form.elements.email.value.trim();
  if (!/^[^@\s]+@[^@\s]+\.[a-z]{2,}$/i.test(email)) {
    e.preventDefault();                             // stop the browser from submitting the form
    console.log(`"${email}" is not a valid email`);
  }
});

const event = new Event("submit", { cancelable: true });
const allowed = form.dispatchEvent(event);          // false when a listener called preventDefault()
console.log("submitted:", allowed, "| defaultPrevented:", event.defaultPrevented);

Output

"asha@" is not a valid email
submitted: false | defaultPrevented: true

Common mistakes

  • Using the result of querySelector without a null check – TypeError when the selector is wrong.
  • getElementById("#id") – no # for getElementById.
  • Putting user input into innerHTML – XSS; use textContent.
  • element.innerHTML += … – re-creates all children and loses their listeners.
  • Calling forEach/map on an HTMLCollection – convert with [...collection] or Array.from.
  • Removing items while looping over a live collection – items are skipped.
  • removeEventListener with a new function – it must be the same function reference.
  • Running a script before the elements exist – use defer or DOMContentLoaded.

Key points to remember

  • querySelector → first match or null; querySelectorAll → static NodeList.
  • getElementsBy… → live HTMLCollection.
  • textContent for text, innerHTML only for trusted HTML.
  • Attributes are the HTML; properties are the live state (input.value).
  • Events capture down, then bubble up; delegation uses bubbling.
  • preventDefault stops the browser action; stopPropagation stops the journey.
  • Batch many insertions with a DocumentFragment.

Frequently asked questions

Is the DOM the same as my HTML?

No. The DOM starts from the HTML but is a live tree that scripts change; "View source" shows the original HTML, the developer tools show the current DOM.

Why does my script say the element is null?

Either the selector is wrong or the script ran before the element was parsed. Put scripts at the end of body, add defer, or wait for DOMContentLoaded.

What is the virtual DOM?

A JavaScript copy of the UI used by libraries such as React: they compare the old and new copies and apply only the needed changes to the real DOM.

Where can I learn more?

Read DOM manipulation and Events in the JavaScript tutorial, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About JavaScript Programming

Why it matters

  • JavaScript runs every web page and, with Node.js, servers, tools and APIs – it is the most used language in the world
  • Front-end, full-stack and MERN roles test JavaScript first, and many campus coding rounds allow it
  • "Predict the output" questions on hoisting, closures, this, coercion and the event loop are interview favourites
  • Modern ES6+ – let/const, arrow functions, destructuring, promises and async/await – is what companies expect from freshers

Who it is for

  • College students (B.Tech, BCA, MCA, B.Sc CS) learning web development and preparing for semester exams and viva
  • Freshers preparing for campus placements, online assessments and front-end interviews
  • Developers moving to React, Angular, Vue or Node.js who need strong core JavaScript
  • Anyone revising ES6 and asynchronous JavaScript before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs on concepts and ES6 features
  • "Predict the output" puzzles – hoisting, coercion, closures, promises and timers
  • "Find the error" debugging: SyntaxError, ReferenceError, TypeError and silent logic bugs
  • Coding problems with solutions and real output, every one run on Node.js – run any study example in your browser

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture, Cognizant tests
  • Front-end developer interviews
  • MERN / full-stack interviews
  • Online coding assessments
  • University practicals

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, debugging, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links