Module 7: DOM and Browser APIs
Creating and Updating DOM Elements
Change page content, classes, and attributes safely with DOM APIs.
You can update an element's text with textContent, change styling through classes, and create nodes with document.createElement.
const list = document.querySelector("#topics");
if (list) {
const item = document.createElement("li");
item.textContent = "Asynchronous JavaScript";
item.classList.add("topic-item");
list.append(item);
}
Use classList.add, remove, toggle, and contains instead of replacing the entire class string when changing one class. Use DOM properties or setAttribute for attributes according to their meaning.
Replace and remove#
append adds nodes or text to an element; prepend inserts at the beginning; replaceChildren replaces current children; and remove removes an element from its parent. Prefer building nodes with these APIs when content includes external values.
Avoid unsafe HTML injection#
Assigning untrusted text to innerHTML can allow cross-site scripting (XSS) if it contains executable markup. Use textContent for plain text. If rich HTML is required, use a carefully maintained sanitizer and a clear trust boundary.
Accessibility#
When creating interactive elements, make sure users can understand and operate them with a keyboard. Use real buttons for actions, labels for form controls, and meaningful link text rather than clickable generic containers.
Practice#
Build a function that adds a new topic to a list using createElement and textContent. Test with text containing characters such as < and & to confirm they appear as text.