JavaScript Interview Question #55
How do you create and insert a new DOM element?
DOM, Events & Event Loop Fundamentals Mid-Level Intermediate
Quick Interview Answer
Use document.createElement to create an element, configure its content, attributes, classes, or other properties, and then insert it with methods such as append, appendChild, prepend, before, or after.
Detailed Explanation
Use document.createElement to create an element, configure its content, attributes, classes, or other properties, and then insert it with methods such as append, appendChild, prepend, before, or after.
Creating elements through DOM APIs is often preferable when content includes untrusted data because textContent can safely insert text without interpreting it as HTML.
Code Example
const li = document.createElement("li");
li.classList.add("item");
li.textContent = "New interview question";
const list = document.querySelector("#questions");
list.append(li);