Practice Questions — Creating and Removing DOM Elements
← Back to NotesTopic-Specific Questions
Question 1
Easy
What appears on the page after this code runs?
<div id="box"></div>
<script>
const p = document.createElement("p");
p.textContent = "Hello from JavaScript!";
document.getElementById("box").appendChild(p);
</script>createElement creates an element, textContent sets its text, appendChild adds it.
The div now contains a paragraph that says "Hello from JavaScript!".
Question 2
Easy
What is the HTML inside #container after this code?
<div id="container">
<p>Original</p>
</div>
<script>
const newP = document.createElement("p");
newP.textContent = "New";
document.getElementById("container").appendChild(newP);
</script>appendChild adds at the end.
The container has two paragraphs: "Original" (first) and "New" (second).
Question 3
Easy
What is the HTML inside #container after this code?
<div id="container">
<p>Original</p>
</div>
<script>
const newP = document.createElement("p");
newP.textContent = "First!";
document.getElementById("container").prepend(newP);
</script>prepend adds at the beginning.
The container has two paragraphs: "First!" (first) and "Original" (second).
Question 4
Easy
What happens after this code runs?
<ul id="list">
<li>Apple</li>
<li id="banana">Banana</li>
<li>Cherry</li>
</ul>
<script>
document.getElementById("banana").remove();
</script>remove() removes the element from the DOM.
The list now contains only "Apple" and "Cherry". "Banana" is removed.
Question 5
Easy
What appears on the page?
<div id="box"></div>
<script>
const div = document.createElement("div");
div.className = "card";
div.id = "my-card";
div.textContent = "Card content";
document.getElementById("box").appendChild(div);
console.log(div.className);
console.log(div.id);
</script>className sets the class, id sets the id.
A div with text "Card content" appears inside #box. Console logs:
card and my-card.Question 6
Medium
What does the list contain after this code?
<ul id="list">
<li>A</li>
<li id="target">B</li>
<li>C</li>
</ul>
<script>
const list = document.getElementById("list");
const target = document.getElementById("target");
const newLi = document.createElement("li");
newLi.textContent = "X";
list.insertBefore(newLi, target);
</script>insertBefore places the new element before the reference element.
The list contains: A, X, B, C (in that order).
Question 7
Medium
What does the page show?
<p id="old">Old text</p>
<script>
const oldP = document.getElementById("old");
const newP = document.createElement("p");
newP.textContent = "New text";
newP.style.color = "green";
oldP.replaceWith(newP);
</script>replaceWith swaps the old element for the new one.
The page shows a green paragraph with text "New text". The old paragraph is gone.
Question 8
Medium
What is logged?
<div id="box">
<p>One</p>
<p>Two</p>
<p>Three</p>
</div>
<script>
const box = document.getElementById("box");
console.log(box.children.length);
console.log(box.firstElementChild.textContent);
console.log(box.lastElementChild.textContent);
</script>children returns element children. firstElementChild and lastElementChild are the first and last.
3OneThreeQuestion 9
Medium
What is logged?
<div id="box"><p>Hello</p></div>
<script>
const box = document.getElementById("box");
const original = box.firstElementChild;
const clone = original.cloneNode(true);
clone.textContent = "World";
box.appendChild(clone);
console.log(original.textContent);
console.log(clone.textContent);
console.log(box.children.length);
</script>cloneNode creates an independent copy. Changing the clone does not affect the original.
HelloWorld2Question 10
Hard
What is the final HTML inside #container?
<div id="container"></div>
<script>
const container = document.getElementById("container");
const p = document.createElement("p");
p.textContent = "Only one";
container.appendChild(p);
container.appendChild(p);
container.appendChild(p);
</script>An element can only exist in one place. Appending it again moves it.
The container has one paragraph: "Only one".
Question 11
Hard
What is logged?
<ul id="list">
<li>A</li>
<li>B</li>
<li>C</li>
</ul>
<script>
const list = document.getElementById("list");
while (list.firstChild) {
list.removeChild(list.firstChild);
}
console.log(list.children.length);
console.log(list.innerHTML);
</script>The while loop keeps removing the first child until there are none left.
0 (empty string)Question 12
Hard
What is logged?
<div id="box"></div>
<script>
const box = document.getElementById("box");
const fragment = document.createDocumentFragment();
for (let i = 1; i <= 3; i++) {
const p = document.createElement("p");
p.textContent = "Item " + i;
fragment.appendChild(p);
}
console.log(fragment.childNodes.length);
console.log(box.children.length);
box.appendChild(fragment);
console.log(fragment.childNodes.length);
console.log(box.children.length);
</script>After appending a fragment, its children move to the parent. The fragment becomes empty.
3003Question 13
Medium
What does the page show?
<div id="container">
<p>First</p>
<p>Third</p>
</div>
<script>
const container = document.getElementById("container");
const third = container.children[1]; // The "Third" paragraph
const second = document.createElement("p");
second.textContent = "Second";
container.insertBefore(second, third);
</script>insertBefore(new, reference) places new before reference.
The page shows three paragraphs: "First", "Second", "Third".
Question 14
Hard
What is the result?
<div id="box">
<p>Original <strong>bold</strong> text</p>
</div>
<script>
const p = document.querySelector("#box p");
const shallow = p.cloneNode(false);
const deep = p.cloneNode(true);
console.log(shallow.childNodes.length);
console.log(deep.childNodes.length);
console.log(shallow.textContent);
console.log(deep.textContent);
</script>cloneNode(false) copies only the element. cloneNode(true) copies children too.
03 (empty string)Original bold textQuestion 15
Easy
What does the page show?
<div id="box"></div>
<script>
const box = document.getElementById("box");
const h2 = document.createElement("h2");
h2.textContent = "Welcome, Aarav!";
h2.style.color = "#a855f7";
box.appendChild(h2);
</script>Create an h2, set its text and color, then append it.
A purple heading that says "Welcome, Aarav!" appears inside the div.
Question 16
Medium
What is logged?
<ul id="list">
<li>A</li>
<li>B</li>
<li>C</li>
</ul>
<script>
const list = document.getElementById("list");
const items = list.querySelectorAll("li");
items.forEach(function(item) {
const span = document.createElement("span");
span.textContent = " [done]";
item.appendChild(span);
});
console.log(list.textContent.trim().replace(/\s+/g, ' '));
</script>Each li gets a span appended to it with ' [done]'.
A [done] B [done] C [done]Mixed & Application Questions
Question 1
Easy
What does the page show?
<ul id="list"></ul>
<script>
const fruits = ["Apple", "Banana", "Cherry"];
const list = document.getElementById("list");
fruits.forEach(function(fruit) {
const li = document.createElement("li");
li.textContent = fruit;
list.appendChild(li);
});
</script>forEach loops through the array and creates an li for each fruit.
A list with three items: Apple, Banana, Cherry.
Question 2
Easy
What is logged?
<div id="parent">
<p>Child 1</p>
<p>Child 2</p>
</div>
<script>
const parent = document.getElementById("parent");
console.log(parent.childElementCount);
parent.innerHTML = "";
console.log(parent.childElementCount);
</script>childElementCount tells you how many child elements exist. innerHTML = '' empties the element.
20Question 3
Medium
What does the page show after this code?
<div id="container"></div>
<script>
const students = [
{ name: "Aarav", score: 95 },
{ name: "Priya", score: 88 },
{ name: "Rohan", score: 72 }
];
const container = document.getElementById("container");
students.forEach(function(s) {
const div = document.createElement("div");
const name = document.createElement("strong");
name.textContent = s.name;
const score = document.createElement("span");
score.textContent = " - Score: " + s.score;
div.appendChild(name);
div.appendChild(score);
container.appendChild(div);
});
</script>Each student gets a div with a bold name and a score span.
Three divs appear: "Aarav - Score: 95", "Priya - Score: 88", "Rohan - Score: 72".
Question 4
Easy
What is the difference between
appendChild and prepend?Think about where the new element is placed.
appendChild adds an element as the last child of the parent. prepend adds it as the first child. Both add the element inside the parent, but at different positions.Question 5
Medium
Why is
innerHTML += problematic when existing elements have event listeners?Think about what happens to the existing elements.
innerHTML += reads the current HTML as a string, appends the new content, and then completely re-parses and rebuilds all the inner HTML. This destroys the original DOM nodes along with their event listeners. The elements look the same but they are actually new elements without any listeners. Use appendChild or prepend to preserve existing elements and their listeners.Question 6
Medium
What is a DocumentFragment and when should you use it?
Think about performance when adding many elements.
A DocumentFragment is an invisible, lightweight container that exists only in memory. You can add many elements to a fragment without triggering DOM re-renders. When you finally append the fragment to the page, all its children are transferred in a single operation. Use it when creating many elements in a loop (like 100+ list items) to improve performance.
Question 7
Hard
What is the result?
<div id="a"></div>
<div id="b"></div>
<script>
const p = document.createElement("p");
p.textContent = "Shared";
document.getElementById("a").appendChild(p);
console.log(document.getElementById("a").children.length);
console.log(document.getElementById("b").children.length);
document.getElementById("b").appendChild(p);
console.log(document.getElementById("a").children.length);
console.log(document.getElementById("b").children.length);
</script>An element can only exist in one parent. Appending it elsewhere moves it.
1001Question 8
Hard
What does the page show?
<ul id="list">
<li>Keep</li>
<li class="remove">Remove 1</li>
<li>Keep</li>
<li class="remove">Remove 2</li>
<li>Keep</li>
</ul>
<script>
const toRemove = document.querySelectorAll(".remove");
toRemove.forEach(function(el) {
el.remove();
});
console.log(document.getElementById("list").children.length);
</script>querySelectorAll captures all .remove elements, then forEach removes each one.
The list shows three "Keep" items. Console logs:
3.Question 9
Medium
What is logged?
<div id="box"></div>
<script>
const box = document.getElementById("box");
const p1 = document.createElement("p");
p1.textContent = "First";
const p2 = document.createElement("p");
p2.textContent = "Second";
box.append(p1, " and ", p2);
console.log(box.innerHTML);
</script>append() can take multiple arguments, including strings.
<p>First</p> and <p>Second</p>Question 10
Hard
What is logged?
<div id="box"><p>Hello</p></div>
<script>
const box = document.getElementById("box");
const p = box.firstElementChild;
p.remove();
console.log(box.children.length);
console.log(p.textContent);
console.log(p.parentNode);
</script>After remove(), the element still exists in memory but has no parent.
0HellonullQuestion 11
Easy
What is the HTML inside the ul after this code?
<ul id="list"></ul>
<script>
const list = document.getElementById("list");
const li1 = document.createElement("li");
li1.textContent = "First";
const li2 = document.createElement("li");
li2.textContent = "Second";
list.appendChild(li1);
list.prepend(li2);
</script>appendChild adds at the end, prepend adds at the beginning.
The ul contains: Second (first), then First (second).
Question 12
Medium
What happens?
<div id="container">
<p id="a">A</p>
<p id="b">B</p>
<p id="c">C</p>
</div>
<script>
const container = document.getElementById("container");
const c = document.getElementById("c");
container.insertBefore(c, container.firstElementChild);
console.log(container.children[0].textContent);
console.log(container.children[1].textContent);
console.log(container.children[2].textContent);
</script>insertBefore moves existing elements, not copies them.
CABQuestion 13
Medium
What is logged?
<template id="tmpl">
<div class="card">
<h3 class="title"></h3>
<p class="body"></p>
</div>
</template>
<script>
const tmpl = document.getElementById("tmpl");
console.log(tmpl.innerHTML.includes("card"));
console.log(tmpl.content instanceof DocumentFragment);
console.log(document.querySelectorAll(".card").length);
</script>Template content is not rendered in the DOM. It exists only in the template's content property.
truetrue0Question 14
Hard
What is logged?
<div id="box"></div>
<script>
const box = document.getElementById("box");
box.innerHTML = "<p>Hello</p>";
const p1 = box.firstElementChild;
box.innerHTML = "<p>Hello</p>";
const p2 = box.firstElementChild;
console.log(p1.textContent);
console.log(p2.textContent);
console.log(p1 === p2);
</script>Setting innerHTML destroys old elements and creates new ones.
HelloHellofalseQuestion 15
Hard
When should you use
innerHTML and when should you use createElement?Think about security, performance, and event listeners.
Use
innerHTML when: (1) you need to set a large chunk of trusted, static HTML quickly, and (2) the content does not come from user input. Use createElement when: (1) the content includes user input (for XSS safety), (2) existing elements have event listeners you want to preserve, and (3) you need references to the created elements for further manipulation.Multiple Choice Questions
MCQ 1
Which method creates a new HTML element?
Answer: B
B is correct.
B is correct.
document.createElement('tag') creates a new element. The other methods do not exist in the DOM API.MCQ 2
Where does
appendChild place the new element?Answer: B
B is correct.
B is correct.
appendChild adds the new element as the last child of the parent. To add as the first child, use prepend.MCQ 3
How do you remove an element from the DOM?
Answer: C
C is correct.
C is correct.
element.remove() removes the element from the DOM. delete and destroy are not DOM methods. hide does not exist (you would use CSS for hiding).MCQ 4
What happens if you call
createElement but never appendChild?Answer: C
C is correct.
C is correct.
createElement creates an element in JavaScript's memory. It has no parent and is invisible. You must explicitly append it to a visible element for it to appear.MCQ 5
What does
element.replaceWith(newElement) do?Answer: B
B is correct.
B is correct.
replaceWith removes the original element from the DOM and inserts the new element exactly where the old one was.MCQ 6
What is the danger of using
innerHTML with user input?Answer: C
C is correct.
C is correct.
innerHTML parses strings as HTML. If user input contains malicious scripts (like <script> tags or event handlers), they get executed. Always use textContent for user input.MCQ 7
What happens when you append the same element to a different parent?
Answer: B
B is correct. A DOM element can only have one parent. Appending it to a new parent moves it from the old one. To have it in both places, use
B is correct. A DOM element can only have one parent. Appending it to a new parent moves it from the old one. To have it in both places, use
cloneNode(true).MCQ 8
What does
cloneNode(true) do compared to cloneNode(false)?Answer: A
A is correct.
A is correct.
cloneNode(true) creates a deep clone: the element AND all its children and their text. cloneNode(false) clones only the element itself, with no children.MCQ 9
Why does
innerHTML += destroy event listeners on existing elements?Answer: B
B is correct.
B is correct.
innerHTML += serializes current content to a string, concatenates the new string, then re-parses the entire result. The old DOM nodes (with their listeners) are destroyed and replaced with new ones that look the same but have no listeners.MCQ 10
What is a DocumentFragment?
Answer: C
C is correct. A DocumentFragment is a minimal document object that is not part of the active DOM tree. You can add elements to it without triggering re-renders, then append the fragment to add all elements at once.
C is correct. A DocumentFragment is a minimal document object that is not part of the active DOM tree. You can add elements to it without triggering re-renders, then append the fragment to add all elements at once.
MCQ 11
Which method adds an element as the first child of a parent?
Answer: B
B is correct.
B is correct.
prepend adds an element at the beginning (first child). appendChild adds at the end. insertBefore can also achieve this but requires a reference to the current first child.MCQ 12
What does the
append method accept that appendChild does not?Answer: A
A is correct.
A is correct.
append() can take multiple arguments and accepts both elements and strings. appendChild() accepts only a single node and returns the appended node.MCQ 13
After calling
element.remove(), what happens to JavaScript variables referencing that element?Answer: C
C is correct.
C is correct.
remove() detaches the element from the DOM, but the JavaScript variable still references the element object in memory. Its parentNode becomes null, but you can still read its properties or even re-append it.MCQ 14
What does
insertBefore(newNode, null) do?Answer: C
C is correct. When the reference node is
C is correct. When the reference node is
null, insertBefore appends the new node at the end of the parent's children, behaving exactly like appendChild.MCQ 15
What does
element.textContent = '' do?Answer: B
B is correct. Setting textContent to an empty string removes all child nodes (text and elements) from inside the element. The element itself remains in the DOM, just empty.
B is correct. Setting textContent to an empty string removes all child nodes (text and elements) from inside the element. The element itself remains in the DOM, just empty.
MCQ 16
What is the difference between
append() and appendChild()?Answer: A
A is correct.
A is correct.
append() can accept multiple arguments including strings and nodes. appendChild() takes only a single DOM node and returns the appended node.MCQ 17
What does
parentNode return for an element that has been removed with remove()?Answer: C
C is correct. After calling
C is correct. After calling
remove(), the element is detached from the DOM. Its parentNode becomes null because it no longer has a parent.MCQ 18
Why is
DocumentFragment better than appending elements one by one in a loop?Answer: B
B is correct. Each
B is correct. Each
appendChild call on a visible element can trigger the browser to re-render. A DocumentFragment is an invisible container; building elements there does not trigger renders. Appending the fragment causes just one re-render.MCQ 19
What method creates a text node (not an element)?
Answer: B
B is correct.
B is correct.
document.createTextNode('some text') creates a text node. This is rarely needed because textContent is simpler, but it is useful for precise text insertion.Coding Challenges
Challenge 1: Dynamic Shopping List
EasyCreate a page with an input field and an 'Add Item' button. When the button is clicked, add the input text as a new list item. Each list item should have a 'Remove' button that deletes it. Show the total count of items above the list.
Sample Input
Type 'Milk' and click Add Item
Sample Output
List item 'Milk' appears with a remove button. Count shows '1 item'.
Use createElement, appendChild, remove. Use textContent for the item text.
<!DOCTYPE html>
<html>
<body>
<h2>Shopping List</h2>
<input type="text" id="item" placeholder="Add item..."><button id="add">Add Item</button>
<p id="count">0 items</p>
<ul id="list"></ul>
<script>
const list = document.getElementById("list");
const count = document.getElementById("count");
function updateCount() { count.textContent = list.children.length + " item" + (list.children.length !== 1 ? "s" : ""); }
document.getElementById("add").addEventListener("click", function() {
const text = document.getElementById("item").value.trim();
if (text) {
const li = document.createElement("li");
li.textContent = text + " ";
const btn = document.createElement("button");
btn.textContent = "Remove";
btn.addEventListener("click", function() { li.remove(); updateCount(); });
li.appendChild(btn);
list.appendChild(li);
document.getElementById("item").value = "";
updateCount();
}
});
</script>
</body>
</html>Challenge 2: Student Cards from Array
EasyGiven an array of student objects [{name, age, city}], create a card for each student and add them to the page. Each card should show the name (bold), age, and city. Use a DocumentFragment for performance.
Sample Input
const students = [{name:'Aarav',age:15,city:'Delhi'},{name:'Priya',age:14,city:'Mumbai'},{name:'Rohan',age:16,city:'Pune'}]
Sample Output
Three styled cards appear on the page with student info.
Use createElement, DocumentFragment, textContent. Do not use innerHTML.
<!DOCTYPE html>
<html>
<head><style>.card{padding:16px;margin:8px 0;border:1px solid #ddd;border-radius:8px;} .card .name{font-weight:bold;font-size:18px;}</style></head>
<body>
<h2>Students</h2>
<div id="container"></div>
<script>
const students = [{name:'Aarav',age:15,city:'Delhi'},{name:'Priya',age:14,city:'Mumbai'},{name:'Rohan',age:16,city:'Pune'}];
const fragment = document.createDocumentFragment();
students.forEach(function(s) {
const card = document.createElement("div");
card.className = "card";
const name = document.createElement("div");
name.className = "name";
name.textContent = s.name;
const info = document.createElement("div");
info.textContent = "Age: " + s.age + " | City: " + s.city;
card.appendChild(name);
card.appendChild(info);
fragment.appendChild(card);
});
document.getElementById("container").appendChild(fragment);
</script>
</body>
</html>Challenge 3: Notification Stack
MediumBuild a notification system. Add buttons for 'Info', 'Success', 'Warning', and 'Error' notifications. Each notification appears at the top of a stack, shows a message and type, has a close button, and auto-removes after 5 seconds. Use different background colors for each type.
Sample Input
Click 'Success' button
Sample Output
A green notification appears saying 'Success: Operation completed!' with an 'x' button. It disappears after 5 seconds.
Use createElement, prepend, remove, setTimeout. Use classList for type-based styling.
<!DOCTYPE html>
<html>
<head><style>.notif{padding:12px;margin:6px 0;border-radius:6px;display:flex;justify-content:space-between;} .info{background:#dbeafe;} .success{background:#d1fae5;} .warning{background:#fef3c7;} .error{background:#fecaca;} .close{background:none;border:none;cursor:pointer;font-size:16px;}</style></head>
<body>
<button id="info">Info</button><button id="success">Success</button><button id="warning">Warning</button><button id="error">Error</button>
<div id="stack"></div>
<script>
function notify(type, msg) {
const div = document.createElement("div");
div.className = "notif " + type;
const text = document.createElement("span");
text.textContent = type.charAt(0).toUpperCase() + type.slice(1) + ": " + msg;
const btn = document.createElement("button");
btn.className = "close";
btn.textContent = "x";
btn.addEventListener("click", function() { div.remove(); });
div.appendChild(text);
div.appendChild(btn);
document.getElementById("stack").prepend(div);
setTimeout(function() { if (div.parentNode) div.remove(); }, 5000);
}
document.getElementById("info").addEventListener("click", function() { notify("info", "Here is some information."); });
document.getElementById("success").addEventListener("click", function() { notify("success", "Operation completed!"); });
document.getElementById("warning").addEventListener("click", function() { notify("warning", "Check your input."); });
document.getElementById("error").addEventListener("click", function() { notify("error", "Something went wrong."); });
</script>
</body>
</html>Challenge 4: Sortable List with Move Up/Down
MediumCreate a list of 5 items. Each item has 'Move Up' and 'Move Down' buttons. Clicking 'Move Up' moves the item one position up in the list. Clicking 'Move Down' moves it one position down. The first item should not move up, and the last should not move down.
Sample Input
Click 'Move Up' on the third item
Sample Output
The third item moves to the second position.
Use insertBefore for moving. Check if the element is first or last before moving.
<!DOCTYPE html>
<html>
<head><style>li{padding:10px;margin:4px 0;background:#f3f4f6;border-radius:4px;display:flex;justify-content:space-between;align-items:center;} button{padding:4px 8px;margin:0 2px;cursor:pointer;}</style></head>
<body>
<h2>Reorder List</h2>
<ul id="list">
<li>Item 1 <span><button class="up">Up</button><button class="down">Down</button></span></li>
<li>Item 2 <span><button class="up">Up</button><button class="down">Down</button></span></li>
<li>Item 3 <span><button class="up">Up</button><button class="down">Down</button></span></li>
<li>Item 4 <span><button class="up">Up</button><button class="down">Down</button></span></li>
<li>Item 5 <span><button class="up">Up</button><button class="down">Down</button></span></li>
</ul>
<script>
const list = document.getElementById("list");
list.addEventListener("click", function(e) {
const li = e.target.closest("li");
if (!li) return;
if (e.target.classList.contains("up") && li.previousElementSibling) {
list.insertBefore(li, li.previousElementSibling);
}
if (e.target.classList.contains("down") && li.nextElementSibling) {
list.insertBefore(li.nextElementSibling, li);
}
});
</script>
</body>
</html>Challenge 5: Dynamic Table Builder
HardBuild a table generator. The user enters the number of rows and columns. When they click 'Generate', create a table with those dimensions. Each cell should show its row and column number (e.g., 'R1C2'). Add a 'Delete Row' button at the end of each row and a 'Delete Column' button at the top of each column.
Sample Input
Rows: 3, Columns: 4
Sample Output
A 3x4 table with cells labeled R1C1, R1C2, etc. Delete buttons on rows and columns.
Use createElement for table, tr, td, th elements. Use event delegation for delete buttons.
<!DOCTYPE html>
<html>
<head><style>table{border-collapse:collapse;margin:16px 0;} td,th{border:1px solid #ddd;padding:8px;text-align:center;} button{padding:4px 8px;cursor:pointer;}</style></head>
<body>
<h2>Table Builder</h2>
<input type="number" id="rows" value="3" min="1" max="10" style="width:60px;"> rows
<input type="number" id="cols" value="4" min="1" max="10" style="width:60px;"> cols
<button id="gen">Generate</button>
<div id="output"></div>
<script>
document.getElementById("gen").addEventListener("click", function() {
const rows = parseInt(document.getElementById("rows").value);
const cols = parseInt(document.getElementById("cols").value);
const output = document.getElementById("output");
output.innerHTML = "";
const table = document.createElement("table");
for (let r = 1; r <= rows; r++) {
const tr = document.createElement("tr");
for (let c = 1; c <= cols; c++) {
const td = document.createElement("td");
td.textContent = "R" + r + "C" + c;
tr.appendChild(td);
}
const delTd = document.createElement("td");
const delBtn = document.createElement("button");
delBtn.textContent = "Delete Row";
delBtn.addEventListener("click", function() { tr.remove(); });
delTd.appendChild(delBtn);
tr.appendChild(delTd);
table.appendChild(tr);
}
output.appendChild(table);
});
</script>
</body>
</html>Challenge 6: Bookmark Manager
HardBuild a bookmark manager. Users can add bookmarks with a title and URL. Each bookmark is displayed as a card with the title (as a clickable link), URL text, and a 'Delete' button. Add a search input that filters bookmarks by title in real time. Use textContent for the title (for XSS safety) and setAttribute for the href.
Sample Input
Title: 'Google', URL: 'https://google.com'
Sample Output
A bookmark card appears with 'Google' as a clickable link and a delete button.
Use createElement for everything. Use textContent for user input. Use setAttribute for href. Use a DocumentFragment when initially rendering.
<!DOCTYPE html>
<html>
<head><style>.card{padding:12px;margin:8px 0;border:1px solid #ddd;border-radius:8px;display:flex;justify-content:space-between;align-items:center;} .card a{font-weight:bold;color:#a855f7;} .card .url{font-size:12px;color:#9ca3af;} button{padding:4px 12px;cursor:pointer;} input{padding:8px;margin:4px;border:1px solid #ddd;border-radius:4px;}</style></head>
<body>
<h2>Bookmarks</h2>
<input type="text" id="title" placeholder="Title">
<input type="url" id="url" placeholder="URL">
<button id="add">Add</button>
<input type="text" id="search" placeholder="Search bookmarks..." style="display:block;margin-top:12px;width:300px;">
<div id="bookmarks"></div>
<script>
const container = document.getElementById("bookmarks");
document.getElementById("add").addEventListener("click", function() {
const title = document.getElementById("title").value.trim();
const url = document.getElementById("url").value.trim();
if (title && url) {
const card = document.createElement("div");
card.className = "card";
card.setAttribute("data-title", title.toLowerCase());
const info = document.createElement("div");
const link = document.createElement("a");
link.textContent = title;
link.setAttribute("href", url);
link.setAttribute("target", "_blank");
const urlText = document.createElement("div");
urlText.className = "url";
urlText.textContent = url;
info.appendChild(link);
info.appendChild(urlText);
const del = document.createElement("button");
del.textContent = "Delete";
del.addEventListener("click", function() { card.remove(); });
card.appendChild(info);
card.appendChild(del);
container.appendChild(card);
document.getElementById("title").value = "";
document.getElementById("url").value = "";
}
});
document.getElementById("search").addEventListener("input", function() {
const q = this.value.toLowerCase();
document.querySelectorAll(".card").forEach(function(card) {
card.style.display = card.getAttribute("data-title").includes(q) ? "flex" : "none";
});
});
</script>
</body>
</html>Need to Review the Concepts?
Go back to the detailed notes for this chapter.
Read Chapter NotesWant to learn web development with a live mentor?
Explore our Frontend Masterclass