Extended DOM Operations

1. Creating Elements

You can create HTML elements dynamically using document.createElement().

const newDiv = document.createElement("div");
newDiv.textContent = "I am a new DIV!";

2. Appending Elements

To add the element to the DOM, use appendChild() or append().

document.body.appendChild(newDiv);

append() can also add strings or multiple elements at once.

3. Styling Elements

Use element.style to apply CSS directly via JavaScript.

newDiv.style.color = "white";
newDiv.style.backgroundColor = "teal";
newDiv.style.padding = "10px";

4. Adding Event Listeners

You can add interactive behavior using addEventListener().

newDiv.addEventListener("click", () => {
  alert("You clicked the div!");
});

5. Removing Elements

Use remove() to delete an element from the DOM.

newDiv.remove();

6. Replacing Elements

You can replace one element with another using replaceChild().

const newPara = document.createElement("p");
newPara.textContent = "I am replacing the div!";
document.body.replaceChild(newPara, newDiv);

7. innerHTML vs textContent

innerHTML sets HTML content. textContent sets only plain text.

element.innerHTML = "<strong>Bold Text</strong>";
element.textContent = "<strong>Not Bold</strong>";

Live Demo Example


// JS
document.getElementById("addBtn").addEventListener("click", () => {
  const box = document.createElement("div");
  box.textContent = "New Box";
  box.style.backgroundColor = "#22c55e";
  box.style.color = "#fff";
  box.style.margin = "10px 0";
  box.style.padding = "10px";
  box.style.borderRadius = "6px";
  document.getElementById("boxContainer").appendChild(box);
});
      

Glossary

References