Advance JavaScript (DOM, BOM, Web API) / Document Object Model

Manipulating Elements - Part 3

✅ replaceChild() – replace a child element by a new element.

🔹 What is replaceChild()?

  • replaceChild() is a DOM method used to replace an existing child node with a new node.

  • It works on the parent node.

✏️ Syntax

parentNode.replaceChild(newChild, oldChild);

💊 Parameters

  • newChild → The new node that will replace the old one

  • oldChild → The existing child node to be replaced

👉 Key Points

  • Replaces only child nodes of a parent

  • The position of the old node remains the same

  • Returns: the replaced (old) node

  • Throws an error if oldChild is not a child of parentNode

1️⃣ Replace an element example

✏️ HTML

<ul id="menu">
  <li>Homepage</li>
  <li>Services</li>
  <li>About</li>
  <li>Contact</li>
</ul>

🧠 JavaScript

const menu = document.getElementById('menu');

// create a new <li>
const li = document.createElement('li');
li.textContent = 'Home';

// replace the first list item
menu.replaceChild(li, menu.firstElementChild);
<ul id="menu">
  <li>Home</li>
  <li>Services</li>
  <li>About</li>
  <li>Contact</li>
</ul>

📌 The first <li> (Homepage) is replaced with Home.

🧠 How it works

  1. Select the parent element (ul)

  2. Create a new element (li)

  3. Replace the old child using replaceChild()

🔁 Modern Alternative

 // select the element to be replaced
 const firstItem = document.querySelector('#menu li');

 // create a new element
 const newLi = document.createElement('li');
 newLi.textContent = 'Home';

 // replace the old element
 firstItem.replaceWith(newLi);

✔️ Simpler

✔️ No parent reference needed


✅ cloneNode() – clone an element and all of its descendants

🔹 What is cloneNode()?

  • cloneNode() is a DOM method used to create a copy of an existing node.

  • It belongs to the Node interface.

✏️ Syntax

const clonedNode = originalNode.cloneNode(deep);

💊 Parameters

deep (optional)

  • true → Clones the node and all its child elements

  • false → Clones only the node itself (no children)

  • Default: false

👀 Return Value

  • Returns a new copy of the original node

❗️ Important Usage Notes

  • Copies:

    • HTML structure

    • Attributes

    • Inline event handlers (e.g., onclick="")

  • ❌ Does NOT copy:

    • Event listeners added using addEventListener()

  • ⚠️ If the cloned node has an id, it will be duplicated

    → Always change the id before inserting into DOM

1️⃣ Clone an element with all children (Deep Clone)

✏️ HTML

<ul id="menu">
  <li>Home</li>
  <li>Services</li>
  <li>About</li>
  <li>Contact</li>
</ul>

🧠 JavaScript

const menu = document.querySelector('#menu');

// deep clone (includes children)
const clonedMenu = menu.cloneNode(true);

// change id to avoid duplication
clonedMenu.id = 'menu-mobile';

// insert into DOM
document.body.appendChild(clonedMenu);
<ul id="menu">
  <li>Home</li>
  <li>Services</li>
  <li>About</li>
  <li>Contact</li>
</ul>

<ul id="menu-mobile">
  <li>Home</li>
  <li>Services</li>
  <li>About</li>
  <li>Contact</li>
</ul>

📌 A full copy of the menu is added to the page.

2️⃣ Shallow clone (without children)

🧠 Code

const shallowClone = menu.cloneNode(false);
document.body.appendChild(shallowClone);
<ul id="menu"></ul>

📌 Only the <ul> is cloned — no <li> elements.

🔁 When to Use cloneNode()

  • Creating mobile menus

  • Duplicating cards or templates

  • Reusing UI components


✅ removeChild() – remove child elements of a node

🔹 What is removeChild()?

  • removeChild() is a DOM method used to remove a child node from its parent.

  • It works only when the node is a direct child of the parent.

✏️ Syntax

parentNode.removeChild(childNode);

💊 Parameters

  • childNode → The child node to be removed

❌ If childNode is not a child of parentNode, an error is thrown.

👀 Return Value

  • Returns the removed node

  • The node is removed from DOM, but still exists in memory

1️⃣ Remove a single child element

✏️ HTML

<ul id="menu">
  <li>Home</li>
  <li>Products</li>
  <li>About Us</li>
</ul>

🧠 JavaScript

const menu = document.getElementById('menu');

// remove last item
menu.removeChild(menu.lastElementChild);
<ul id="menu">
  <li>Home</li>
  <li>Products</li>
</ul>

📌 The last <li> is removed.

2️⃣ Store the removed node (optional)

const removedItem = menu.removeChild(menu.firstElementChild);

// still accessible in memory
console.log(removedItem.textContent); // Home

📌 Useful if you want to reinsert later.

3️⃣ Remove all child nodes (loop method)

const menu = document.getElementById('menu');

while (menu.firstChild) {
  menu.removeChild(menu.firstChild);
}

📌 Removes nodes one by one safely.

4️⃣ Remove all children (quick way)

menu.innerHTML = '';

📌 Fast but:

  • ❌ Removes everything instantly

  • ❌ Also removes attached event handlers

🔁 Modern Alternative

element.remove();

Example:

menu.lastElementChild.remove();

✔️ Cleaner

✔️ No parent reference needed


✅ insertBefore() - insert a new node before an existing node as a child node of a specified parent node

🔹 What is insertBefore()?

  • insertBefore() is a DOM method used to insert a new node before an existing child node.

  • It works on the parent node.

✏️ Syntax

parentNode.insertBefore(newNode, existingNode);

💊 Parameters

  • newNode → Node to be inserted

  • existingNode → Node before which the new node is inserted

    • If existingNode is null, the node is added at the end

👀 Return Value

  • Returns the inserted node

1️⃣ Insert an element before another element

✏️ HTML

<ul id="menu">
  <li>Services</li>
  <li>About</li>
  <li>Contact</li>
</ul>

🧠 JavaScript

const menu = document.getElementById('menu');

// create new <li>
const li = document.createElement('li');
li.textContent = 'Home';

// insert before first item
menu.insertBefore(li, menu.firstElementChild);
<ul id="menu">
  <li>Home</li>
  <li>Services</li>
  <li>About</li>
  <li>Contact</li>
</ul>

📌 The new <li> is added at the beginning.

2️⃣ Insert at the end using null

menu.insertBefore(li, null);

📌 Same effect as appendChild().

3️⃣ Helper function (optional)

function insertBefore(newNode, existingNode) {
  existingNode.parentNode.insertBefore(newNode, existingNode);
}

📌 Useful when the parent is not directly available.

🔁 Modern Alternatives

Example:

menu.firstElementChild.before(li);