You can create HTML elements dynamically using document.createElement().
const newDiv = document.createElement("div");
newDiv.textContent = "I am a new DIV!";
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.
Use element.style to apply CSS directly via JavaScript.
newDiv.style.color = "white";
newDiv.style.backgroundColor = "teal";
newDiv.style.padding = "10px";
You can add interactive behavior using addEventListener().
newDiv.addEventListener("click", () => {
alert("You clicked the div!");
});
Use remove() to delete an element from the DOM.
newDiv.remove();
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);
innerHTML sets HTML content. textContent sets only plain text.
element.innerHTML = "<strong>Bold Text</strong>";
element.textContent = "<strong>Not Bold</strong>";
// 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);
});