📘 Lesson · Lesson 35
Creating and Removing Elements
Elements बनाना और हटाना
createElement — making a new element
let p = document.createElement("p"); // creates <p></p> in memory
p.textContent = "I'm new here!";
p.classList.add("highlight");
// ⚠ It's NOT on the page yet — it exists only in memory
console.log(p); // <p class="highlight">I'm new here!</p>
document.createElement("tag") builds a brand-new element, but it isn't visible yet — it floats in memory, unattached to the page. This is a two-step process that trips up beginners: create it, configure it, THEN attach it. Configure it exactly as you'd configure any selected element: set textContent, add classes with classList, set attributes. Only when you append it to an existing element does it appear on screen.Adding Elements to the Page
let box = document.querySelector(".box");
let p = document.createElement("p");
p.textContent = "Hello";
box.appendChild(p); // add as the LAST child (classic)
box.append(p); // same, but also accepts text and multiple items
box.prepend(p); // add as the FIRST child
// Insert before a specific element:
box.insertBefore(p, existingChild);
// The quick way (careful — replaces everything inside):
box.innerHTML += "<p>Hello</p>"; // ✗ destroys and rebuilds children
appendChild() adds an element as the last child of a parent — this is the method you'll use most. The newer append() does the same but can also take plain strings and several items at once. prepend() adds to the start instead. Avoid the tempting innerHTML += shortcut: it re-parses ALL the parent's HTML, destroying and recreating every child — which wipes out any event listeners you attached and hurts performance. Proper element creation is safer and faster.Removing Elements
let item = document.querySelector(".item");
item.remove(); // modern and simple — deletes itself
item.parentNode.removeChild(item); // the older, verbose way
box.innerHTML = ""; // remove ALL children at once
Removing an element is refreshingly simple: call
.remove() on it and it deletes itself from the page. You'll still see the older parentNode.removeChild(child) pattern in existing code — it does the same thing, but requires reaching up to the parent first. To empty a container completely, setting innerHTML = "" is the quickest way. Removing elements powers "delete" buttons, dismissible alerts, and removing items from a to-do list.Navigating the DOM Tree
let item = document.querySelector(".item");
item.parentElement; // go UP to the parent
item.children; // all child ELEMENTS (an HTMLCollection)
item.firstElementChild; // the first child element
item.nextElementSibling; // the element after it
item.previousElementSibling; // the element before it
item.closest(".card"); // nearest ANCESTOR matching a selector
Once you have one element, you can walk to its relatives using the family relationships from the DOM tree. Note the
Element in these names (firstElementChild, nextElementSibling): these skip text nodes and give you only real elements — the versions without "Element" (firstChild, nextSibling) include whitespace text nodes and are usually not what you want. closest() is especially handy: from a clicked delete-button, btn.closest(".card") finds the card it belongs to, so you can remove the whole card.Building Lists from Data — the real-world pattern
let students = ["Aman", "Priya", "Ravi"];
let list = document.querySelector("#studentList");
students.forEach(name => {
let li = document.createElement("li");
li.textContent = name; // safe — no HTML injection
list.appendChild(li);
});
// Building a card from an object:
let student = { name: "Aman", marks: 85 };
let card = document.createElement("div");
card.classList.add("card");
card.innerHTML = `<h3>${student.name}</h3><p>${student.marks}</p>`;
document.body.appendChild(card);
This is the single most common DOM pattern in real applications: take an array of data, loop over it, and build an element for each item. Every product grid, comment list, and search result you've seen was made this way — data comes from a server as JSON, gets parsed into an array of objects, and each object becomes a card on the page. Notice how it combines everything: arrays,
forEach, objects, template literals, and DOM creation. Once this pattern clicks, you can build almost any dynamic interface.Exam Corner
Q: Does createElement() put the element on the page? No — it exists in memory until you append it.
Q: What does appendChild() do? Adds an element as the last child of a parent.
Q: Why avoid
Q: How do you delete an element?
Q: What does closest(".card") do? Finds the nearest ancestor matching that selector.
Q: What does appendChild() do? Adds an element as the last child of a parent.
Q: Why avoid
innerHTML += to add elements? It rebuilds all children, destroying event listeners and hurting performance.Q: How do you delete an element?
element.remove()Q: What does closest(".card") do? Finds the nearest ancestor matching that selector.
createElement — नया element बनाना
let p = document.createElement("p"); // memory me <p></p> banata
p.textContent = "I'm new here!";
p.classList.add("highlight");
// ⚠ Yeh abhi page par NAHI hai — sirf memory me maujood hai
console.log(p); // <p class="highlight">I'm new here!</p>
document.createElement("tag") बिल्कुल नया element बनाता है, पर वह अभी दिखता नहीं — यह memory में तैरता है, page से जुड़ा नहीं. यह दो-कदम प्रक्रिया beginners को उलझाती है: बनाइए, configure कीजिए, PHIR जोड़िए. इसे ठीक वैसे configure कीजिए जैसे किसी भी selected element को: textContent set कीजिए, classList से classes जोड़िए, attributes set कीजिए. सिर्फ जब आप इसे किसी मौजूदा element में append करें, तब यह screen पर दिखता है.Page में Elements जोड़ना
let box = document.querySelector(".box");
let p = document.createElement("p");
p.textContent = "Hello";
box.appendChild(p); // AAKHRI child ke roop me jodo (classic)
box.append(p); // vahi, par text aur kai items bhi lete
box.prepend(p); // PEHLE child ke roop me jodo
// Kisi khaas element se pehle daalo:
box.insertBefore(p, existingChild);
// Jaldi ka tarika (savdhan — andar sab kuch replace):
box.innerHTML += "<p>Hello</p>"; // ✗ children nasht karke dobara banata
appendChild() element को parent के आखिरी child के रूप में जोड़ता है — यही method आप सबसे ज़्यादा use करेंगे. नया append() वही करता है पर सादी strings और एक साथ कई items भी ले सकता है. prepend() बजाय शुरू में जोड़ता है. लुभावने innerHTML += shortcut से बचिए: यह parent का SAARA HTML दोबारा parse करता है, हर child को नष्ट करके फिर बनाते — जो आपके लगाए event listeners मिटा देता है और performance नुकसान करता है. ठीक element creation सुरक्षित और तेज़ है.Elements हटाना
let item = document.querySelector(".item");
item.remove(); // modern aur saral — khud ko delete karta
item.parentNode.removeChild(item); // purana, lamba tarika
box.innerHTML = ""; // ek saath SAARE children hatao
Element हटाना ताज़गी भरा सरल है: उस पर
.remove() call कीजिए और वह खुद को page से delete कर देता है. आप मौजूदा code में पुराना parentNode.removeChild(child) pattern अब भी देखेंगे — यह वही करता है, पर पहले parent तक पहुंचना पड़ता है. Container पूरी तरह खाली करने को innerHTML = "" set करना सबसे तेज़ तरीका है. Elements हटाना "delete" buttons, हटने योग्य alerts, और to-do list से items हटाना चलाता है.DOM Tree में घूमना
let item = document.querySelector(".item");
item.parentElement; // UPAR parent tak jao
item.children; // saare child ELEMENTS (HTMLCollection)
item.firstElementChild; // pehla child element
item.nextElementSibling; // uske baad ka element
item.previousElementSibling; // uske pehle ka element
item.closest(".card"); // nikattam ANCESTOR jo selector se mile
एक element मिलने के बाद, आप DOM tree के पारिवारिक रिश्तों से उसके रिश्तेदारों तक चल सकते हैं. इन नामों में
Element ध्यान दीजिए (firstElementChild, nextElementSibling): ये text nodes छोड़ते हैं और सिर्फ असली elements देते हैं — बिना "Element" वाले versions (firstChild, nextSibling) whitespace text nodes शामिल करते हैं और आमतौर पर वह नहीं जो आप चाहते. closest() खासकर काम का है: click किए delete-button से, btn.closest(".card") वह card ढूंढता है जिसका वह है, तो आप पूरा card हटा सकते हैं.Data से Lists बनाना — असली दुनिया का pattern
let students = ["Aman", "Priya", "Ravi"];
let list = document.querySelector("#studentList");
students.forEach(name => {
let li = document.createElement("li");
li.textContent = name; // surakshit — koi HTML injection nahi
list.appendChild(li);
});
// Object se card banana:
let student = { name: "Aman", marks: 85 };
let card = document.createElement("div");
card.classList.add("card");
card.innerHTML = `<h3>${student.name}</h3><p>${student.marks}</p>`;
document.body.appendChild(card);
असली applications में यह सबसे common DOM pattern है: data की array लीजिए, उस पर loop कीजिए, और हर item के लिए element बनाइए. हर product grid, comment list, और search result जो आपने देखा ऐसे ही बना था — data server से JSON के रूप में आता है, objects की array में parse होता है, और हर object page पर card बनता है. ध्यान दीजिए यह सब कुछ मिलाता है: arrays,
forEach, objects, template literals, और DOM creation. यह pattern समझ आते ही, आप लगभग कोई भी dynamic interface बना सकते हैं.Exam Corner
Q: क्या createElement() element को page पर डालता है? नहीं — append करने तक यह memory में रहता है.
Q: appendChild() क्या करता है? Element को parent के आखिरी child के रूप में जोड़ता है.
Q: Elements जोड़ने को
Q: Element कैसे delete करते हैं?
Q: closest(".card") क्या करता है? उस selector से मिलता निकटतम ancestor ढूंढता है.
Q: appendChild() क्या करता है? Element को parent के आखिरी child के रूप में जोड़ता है.
Q: Elements जोड़ने को
innerHTML += क्यों टालें? यह सारे children दोबारा बनाता है, event listeners नष्ट करते और performance नुकसान करते.Q: Element कैसे delete करते हैं?
element.remove()Q: closest(".card") क्या करता है? उस selector से मिलता निकटतम ancestor ढूंढता है.
💻 Live Code Editor
इस पेज का code यहाँ तैयार है — बदलिए और तुरंत नतीजा देखिए. कुछ install किए बिना.
सब कुछ आपके browser में ही चलता है — कोई server, कोई signup नहीं. JavaScript का
console.log देखने के लिए F12 दबाइए.